我尝试使用反射生成新的className.java文件的make。我对Fields值有问题。
这是我的测试课。
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);
,但第二个字段出现错误。什么不好的想法?
答案 0 :(得分:3)
由于这是一个实例字段,您需要将该类的实例传递给get(clsInstance);
方法:
import qualified Control.Monad.State.Strict as MTL
import Data.Monoid (Sum)
import Control.Lens.Zoom (zoom)
import Control.Lens.Wrapped (_Wrapped')
outer :: (MTL.MonadState (Sum Int) m) => m Int
outer = zoom _Wrapped' inner
inner :: (MTL.MonadState Int m) => m Int
inner = MTL.get
documentation实际上非常清楚:
抛出NullPointerException - 如果指定的对象为null且该字段是实例字段。
答案 1 :(得分:-1)
您无法使用.getDeclaredFields()访问私有字段。您只能访问公共字段。