Using java reflection for nested class static fields accessor throws NullPointerException

Field field = (obj.getClass().getDeclaredClasses()[0])
                       .getDeclaredField("flowerName");//1
field.setAccessible(true);//2
field.set(null, "Rose");//3

      

In the above line of code 3, I am getting a NullPointerException

The class structure that is passed is shown below

public class A{

    public static class B{
        protected String flowerName;
    }

}

      

I want to set the value of this variable FlowerName at runtime using java reflection. But this is throwing a NullPointerException.

I mentioned in some places where it was stated that when you try to access an instance variable and set zero in a set method such as set (null, "Rose") it will throw a null pointer exception. So how do I set the value of flowerName in a static sibling class using java reflection.

+3


source to share


3 answers


Just because a class is static doesn't mean that its fields are also static. In your case, it flowerName

is a non-static field, so it belongs to an instance, not a class, which means you need to pass an instance of your nested class to set it.



Class<?> nested = obj.getClass().getDeclaredClasses()[0];
Object instance = nested.newInstance();

Field field = nested.getDeclaredField("flowerName");// 1
field.setAccessible(true);// 2

field.set(instance, "Rose");// 3
System.out.println(field.get(instance));

      

+4


source


First of all, check how to instantiate your static inner class . After you have done that, just go like this:

//obj is instance of your inner static class.
Field field = (obj.getClass().getDeclaredField("flowerName");
field.setAccessible(true);
field.set(obj, "Rose");

      



You cannot set the value to "null". Please take a look at the method description in the java docs to understand what is going wrong.

+1


source


Normal behavior, the first parameter is an object with a given method.

With regular Java code, you are trying to do something like this:

B b = null;
B.setFlower(value);

      

b is null, so a NullPointerException will be thrown.

You must pass a non-empty object on the third line, not null.

+1


source







All Articles