簡體   English   中英

通過反射獲取 Java 中 class 的公共 static 最終字段/屬性的值

[英]Getting value of public static final field/property of a class in Java via reflection

假設我有一個 class:

public class R {
    public static final int _1st = 0x334455;
}

如何通過反射獲得“_1st”的值?

首先檢索類的字段屬性,然后可以檢索值。 如果您知道類型,您可以使用帶有 null 的 get 方法之一(僅對於靜態字段,實際上對於靜態字段,傳遞給 get 方法的參數將被完全忽略)。 否則,您可以使用 getType 並編寫一個適當的開關,如下所示:

Field f = R.class.getField("_1st");
Class<?> t = f.getType();
if(t == int.class){
    System.out.println(f.getInt(null));
}else if(t == double.class){
    System.out.println(f.getDouble(null));
}...
 R.class.getField("_1st").get(null);

異常處理留給讀者作為練習。

基本上,您通過反射像任何其他字段一樣獲得該字段,但是當您調用 get 方法時,您會傳入一個 null,因為沒有實例可以對其進行操作。

這適用於所有靜態字段,無論它們是最終的。 如果該字段不是公開的,則需要先對其調用setAccessible(true) ,當然,SecurityManager 必須允許所有這些。

我遵循相同的路線(查看生成的 R 類),然后我有一種可怕的感覺,它可能是 Resources 類中的一個函數。 我是對的。

發現這個: Resources::getIdentifier

認為這可能會為人們節省一些時間。 盡管他們在文檔中表示不鼓勵這樣做,但這並不奇怪。

我一直在尋找如何獲得私有static 字段並登陸這里。

對於其他搜索者,方法如下:

public class R {
    private static final int _1st = 0x334455;
}

class ReflectionHacking {
    public static main(String[] args) {
        Field field = R.class.getFieldDeclaration("_1st");
        field.setAccessible(true);
        int privateHidenInt = (Integer)field.get(null);
    }
}

暫無
暫無

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

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