簡體   English   中英

Java反射-獲取字段值

[英]Java reflection - get field value

我嘗試使生成使用反射生成新的className.java文件的類。 我對“字段”值有疑問。

這是我的測試課。

public class ClassTest {
@Deprecated
private int a;


public int[] b;

private final String c = "Hi";
...
}

我嘗試生成字段的方法。

private void writeAttributes(Class<?> cls, PrintWriter writer){
    Field[] atr = cls.getDeclaredFields();
    for (Field field : atr) {

        this.writeAnnotations(writer, field.getDeclaredAnnotations());
        writer.write(Modifier.toString(field.getModifiers())+" " + field.getType().getTypeName()+ " " + field.getName());
        try{
            System.out.println(field);
            // NULL POINTER EXCEPTION there
            Object value = field.get(null);
            if(value!= null){
                writer.write(" = " + value.toString());
            }
        }catch(IllegalAccessException ex){

        }
        writer.write(";");
        this.writeNewLine(writer);
    }
}

錯誤出現在第三字段private final String c = "Hi";

Exception in thread "main" java.lang.NullPointerException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:57)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)

我試過添加field.setAccessible(true); 但是第二個字段出現錯誤。 有什么不好的主意嗎?

由於這是一個實例字段,因此您需要將類的實例傳遞給get方法:

get(clsInstance);

文檔實際上對此非常清楚:

拋出:NullPointerException-如果指定對象為null,並且該字段是實例字段。

您不能使用.getDeclaredFields()訪問私有字段。 您只能訪問公共字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM