Java reflection - get field value -
i try make class generate new classname.java file using reflection. have problem fields value.
here test class.
public class classtest { @deprecated private int a; public int[] b; private final string c = "hi"; ... }
method in try generate fields.
private void writeattributes(class<?> cls, printwriter writer){ field[] atr = cls.getdeclaredfields(); (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); } }
error on third field private final string c = "hi";
exception in thread "main" java.lang.nullpointerexception @ sun.reflect.unsafefieldaccessorimpl.ensureobj(unsafefieldaccessorimpl.java:57) @ sun.reflect.unsafeobjectfieldaccessorimpl.get(unsafeobjectfieldaccessorimpl.java:36)
i have tried add field.setaccessible(true);
there error comes on second field. ideas bad?
since instance field, need pass instance of class get
method:
get(clsinstance);
the documentation pretty clear that:
throws nullpointerexception - if specified object null , field instance field.
Comments
Post a Comment