Java 反射 - 获取字段值
Java reflection - get field value
我尝试 make class 使用反射生成新的 className.java 文件。我对字段值有疑问。
这是我的测试class。
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);
但第二个字段出现错误。有什么不好的想法吗?
由于这是一个实例字段,您需要将 class 的实例传递给 get
方法:
get(clsInstance);
documentation其实很清楚这一点:
Throws NullPointerException - if the specified object is null and the field is an instance field.
您无法使用 .getDeclaredFields() 访问私有字段。您只能访问 public 字段。
我尝试 make class 使用反射生成新的 className.java 文件。我对字段值有疑问。
这是我的测试class。
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);
但第二个字段出现错误。有什么不好的想法吗?
由于这是一个实例字段,您需要将 class 的实例传递给 get
方法:
get(clsInstance);
documentation其实很清楚这一点:
Throws NullPointerException - if the specified object is null and the field is an instance field.
您无法使用 .getDeclaredFields() 访问私有字段。您只能访问 public 字段。