简体   繁体   English

使用java反射访问静态嵌套类的字段的字段会抛出NullPointerException

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

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 在上面的代码行3中,我得到了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. 我想在运行时使用java反射将值设置为此flowerName变量。 But it is throwing NullPointerException. 但它抛出了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. 我在一些地方提到过,其中已经指定当你试图访问实例变量并在set方法中设置null如set(null,“Rose”)时,它将抛出空指针异常。 So then how to set the value of flowerName in the static nexted class using java reflection. 那么如何使用java反射在静态nexted类中设置flowerName的值。

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. 在你的情况下, flowerName是非静态字段,因此它属于实例,而不是类,这意味着要设置它,你需要传递嵌套类的实例。

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));

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. 您不能将Value设置为“null”对象。 Please take a look on method description in java docs in order to understand what's going wrong. 请查看java docs中的方法描述 ,以了解出现了什么问题。

Normal behavior, the first parameter is the objct with the set method will be apply. 正常行为,第一个参数是set方法将被应用的objct。

With regular Java code you are trying to do something like this : 使用常规Java代码,您尝试执行以下操作:

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

b is null so a NullPointerException will be throw. b为null,因此将抛出NullPointerException。

You have to pass a non-null object at 3rd line and not null. 您必须在第3行传递非null对象而不是null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM