java通过反射统计实体类和父类中为空的字段数量
import java.lang.reflect.Field; public class FieldCounter { public static int countNullFields(Object obj) throws IllegalAccessException { int nullFieldCount = 0; Class<?> clazz = obj.getClass(); while (clazz != null) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.get(obj) == null) { nullFieldCount++; } } clazz = clazz.getSuperclass(); } return nullFieldCount; } public static void main(String[] args) throws IllegalAccessException { // 示例类 class Example { String notNull = "value"; String nullField = null; } // 子类示例 class SubExample extends Example { String anotherNullField = null; } // 统计字段数量 SubExample subExample = new SubExample(); int nullFieldCount = countNullFields(subExample); System.out.println("空字段数量: " + nullFieldCount); } }