Java reflection – get field value

I try make class which generate new className.java file using reflection. I have problem with Fields value.

Here is my test class.

public class ClassTest {
@Deprecated
private int a;


public int[] b;

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

Method in which I try generate fields.

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);
    }
}

Error is on third field 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)

I have tried add field.setAccessible(true); but with there error comes on second field. Any ideas what is bad?

Answer

Since this is an instance field, you will need to pass an instance of the class to the get method:

get(clsInstance);

The documentation is actually pretty clear about that:

Throws NullPointerException – if the specified object is null and the field is an instance field.

Leave a Reply

Your email address will not be published. Required fields are marked *