考虑POJO有n个属性。如何获得表示POJO的填充属性(赋值/非空)的百分比值?
POJO是MySql数据库中的一个实体,我正在使用Java,Hibernate和Spring。
答案 0 :(得分:2)
嘿你可以这样做:
public class CountReflection {
public static void main(final String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
PoJo p = new PoJo();
p.setA("a");
Field[] fields = p.getClass().getDeclaredFields();
int amountOfFields = 0;
int amountOfFieldsNotNull = 0;
for (Field field : fields) {
amountOfFields++;
Field declaredField = p.getClass().getDeclaredField(field.getName());
declaredField.setAccessible(true);
Object value = declaredField.get(p);
if (value != null) {
amountOfFieldsNotNull++;
}
}
System.out.println("amountOfFields " + amountOfFields);
System.out.println("amountOfFieldsNotNull " + amountOfFieldsNotNull);
float percent = (amountOfFieldsNotNull * 100.0f) / amountOfFields;
System.out.println("percent of not null " + percent);
}
}
使用PoJo:
public class PoJo {
private String a;
private String b;
private String c;
private String d;
private String e;
public String getA() {
return a;
}
public void setA(final String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(final String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(final String c) {
this.c = c;
}
public String getD() {
return d;
}
public void setD(final String d) {
this.d = d;
}
public String getE() {
return e;
}
public void setE(final String e) {
this.e = e;
}
}