package org.example; import java.lang.reflect.Field; /** * @author 50649 */ public class TestCount { public static int countNullFields(Object entity) throws IllegalAccessException { if (entity == null) { return 0; } int nullFieldCount = 0; Class<?> clazz = entity.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object fieldValue = field.get(entity); if (fieldValue == null) { nullFieldCount++; } } return nullFieldCount; } public static void main(String[] args) throws IllegalAccessException { // 假設有一個實體類 Entity 如下: // class Entity { // String name; // Integer age; // String email; // } Entity entity = new Entity(); entity.name = "John"; entity.email = null; int nullFieldCount = countNullFields(entity); System.out.println("Number of null fields: " + nullFieldCount); } }
package org.example; /** * @author 50649 */ public class Entity { String name; Integer age; String email; }