Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java reflection to access field of static nested class's fields throws NullPointerException

Tags:

java

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

In the above code line number 3, I'm getting the 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 to this flowerName variable at run time using java reflection. But it is throwing NullPointerException.

I referred in some places, wherein it has been specified that when you are trying to access the instance variable and setting null in the set method like set(null, "Rose"), it will throw null pointer exception. So then how to set the value of flowerName in the static nexted class using java reflection.

like image 737
KalpsRam Avatar asked Sep 07 '25 18:09

KalpsRam


1 Answers

Just because class is static, it doesn't mean that its fields are also static. In your case flowerName is non-static field, so it belongs to instance, not class, which means that to set it you need to pass instance of your nested class.

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));
like image 101
Pshemo Avatar answered Sep 09 '25 20:09

Pshemo