Java reflection – get field value

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

Here is my test class.

public class ClassTest {
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());
            // NULL POINTER EXCEPTION there
            Object value = field.get(null);
            if(value!= null){
                writer.write(" = " + value.toString());
        }catch(IllegalAccessException ex){


Error is on third field private final String c = "Hi";

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

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


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


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 *