簡體   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

在上面的代碼行3中,我得到了NullPointerException

傳遞的類結構如下所示

public class A{

    public static class B{
        protected String flowerName;
    }

}

我想在運行時使用java反射將值設置為此flowerName變量。 但它拋出了NullPointerException。

我在一些地方提到過,其中已經指定當你試圖訪問實例變量並在set方法中設置null如set(null,“Rose”)時,它將拋出空指針異常。 那么如何使用java反射在靜態nexted類中設置flowerName的值。

僅僅因為類是靜態的,並不意味着它的字段也是靜態的。 在你的情況下, 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));

首先檢查如何實例化靜態內部類 在你做完之后,就這樣走吧:

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

您不能將Value設置為“null”對象。 請查看java docs中的方法描述 ,以了解出現了什么問題。

正常行為,第一個參數是set方法將被應用的objct。

使用常規Java代碼,您嘗試執行以下操作:

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

b為null,因此將拋出NullPointerException。

您必須在第3行傳遞非null對象而不是null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM