java透過反射統計實體類和父類中為空的欄位數量

红尘沙漏發表於2024-11-27
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);
    }
}

  

相關文章