[英]How to calculate the count of null field from the model dynamically using java
How to calculate profile completion percentage?如何计算个人资料完成百分比? Refer to the below Profile model file, Each attribute is another model(EX: BasicInfo has some 15 elements, need to take the count of this and then finally adding the count of this one to Profile total count).
参考下面的 Profile model 文件,每个属性是另一个模型(例如:BasicInfo 有大约 15 个元素,需要计算这个,然后最后将这个计数添加到 Profile 总数中)。 I need to get BasicInfo count dynamically without adding if condition check for all fields.
我需要动态获取 BasicInfo 计数,而不需要为所有字段添加 if 条件检查。 Refer the below code
参考下面的代码
Logic:逻辑:
// model sample // model 样品
Profile.java
private BasicInfo basicInfo;
private ReligionInfo religionInfo;
private LocationInfo locationInfo;
private ProfessionalInfo professionalInfo;
private FamilyInfo familyInfo;
private LifestyleInfo lifestyleInfo;
private Configuration configuration;
private BasicPreferences basicPreferences;
private ReligionPreferences religionPreferences;
private LocationPreferences locationPreferences;
private ProfessionalPreferences professionalPreferences;
// What I tried // 我试过的
public long getProfileList(String id) {
Profile profile = findById(id);
int count = getBasicInfo(profile);
return count;
}
private int getBasicInfo(Profile profile) {
int counter = 0;
if (ObjectUtils.isEmpty(profile.getBasicInfo().getBirthDate())) {
counter++;
}
if (ObjectUtils.isEmpty(profile.getBasicInfo().getDobt())) {
counter++;
}
return counter;
}
Have you tried reflection ?你试过反射吗? You can get all the declared fields of a class.
您可以获得 class 的所有声明字段。 I coded a tiny method to filter nulls as you asked
我按照您的要求编写了一个小方法来过滤空值
import java.util.*;
import java.util.stream.*;
import java.lang.reflect.Field;
class Example {
private String emptyField;
private String emptyField2;
private String nonNullField = "non null";
}
public class Main {
static boolean isFieldNull(Field field, Object obj) {
try {
return Objects.isNull(field.get(obj));
} catch(IllegalAccessException ignored) {
return false;
}
}
public static void main (String[] args) {
Example main = new Example();
Field[] fields = Example.class.getDeclaredFields();
//For getting access to private fields
Arrays.stream(fields).forEach(f -> f.setAccessible(true));
System.out.println(Arrays.stream(fields)
.filter(f -> isFieldNull(f, main))
.count());
}
Here's the output of this code这是此代码的 output
java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.