Reputation: 41
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.
Upvotes: 4
Views: 1103
Reputation: 124265
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));
Upvotes: 4
Reputation: 9569
First of all check how to instantiate static inner class. After when you will do it, just go that way:
//obj is instance of your inner static class.
Field field = (obj.getClass().getDeclaredField("flowerName");
field.setAccessible(true);
field.set(obj, "Rose");
You can't set Value to "null" object. Please take a look on method description in java docs in order to understand what's going wrong.
Upvotes: 1
Reputation: 1490
Normal behavior, the first parameter is the objct with the set method will be apply.
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 throw.
You have to pass a non-null object at 3rd line and not null.
Upvotes: 1