I have a very big model class, I want to create a toString method for this model. But there're a lot of field in this model, so I try to use a Common model and Java reflection. But the output is include sub model field name, is it posible to remove this ?
I have 1 abstract model class as below:
import java.lang.reflect.*;
public abstract class CommonEntity {
public String getInsertString() {
StringBuilder sb = new StringBuilder();
try {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(this);
if (value != null) {
sb.append("\"" + value.toString() + "\",");
}
}
} catch (Exception e) {
System.out.println(e);
}
return sb.toString();
}
}
And 2 other model extend this common
test:
@Data
public class test extends CommonEntity {
private String name;
private String last;
private test2 test;
}
test2:
@Data
public class test2 extends CommonEntity {
private String name2;
private String last2;
}
And main class:
public static void main(String[] args) {
test a = new test();
a.setName("1");
a.setLast("2");
test2 b = new test2();
b.setLast2("3");
b.setName2("4");
a.setTest(b);
System.out.println(a.getInsertString());
}
Console output :
"1","2","test2(name2=4, last2=3)",
My expectation:
"1","2","4","3,
Is it posible to remove
test2(name2
and
last2
in ouput.
Aucun commentaire:
Enregistrer un commentaire