0

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And is it possible to get value of final non-static fields without instance?
@dsv_dsv No, this kind of fields could be initialized by final int i = new Random().nextInt(); which can have different value in each instance.
-1

You cannot access private fields by using .getDeclaredFields(). You can only access the public fields.

1 Comment

This is simply wrong. It is getFeilds which can access only public fields (including inherited ones), getDeclaredFields returns array with all fields declared in class including private ones.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.