[英]Reflectively accessing a static variable in a Java class
我沒有別的選擇,只能通過反射來訪問一組我無法修改的類。 但是,使用下面主方法中顯示的方法會拋出NullPointerException。 調用f1.get(null)時,空指針在構造函數中為“table”。
我無法預先實例化類,因為唯一的構造函數是顯示的,它是私有的。 所以我也無法明確設置表。
任何人都知道我可以反思地稱呼Legacy.A?
public class Legacy {
public static final Legacy A = new Legacy("A");
public static final Legacy B = new Legacy("B");
private String type0;
private static Map<String, Legacy> table = new HashMap<String, Legacy>();
private Legacy(String id) {
type0 = id;
table.put(type0, this);
}
public static void main(String[] args) throws Exception {
Field f1 = Legacy.class.getDeclaredField("A");
Object o = f1.get(null);
}
}
在“反射==不好!!!”之前
靜態初始化程序的順序是錯誤的,表必須在構造函數調用之前。
這是在加載和初始化類時獲得異常的原因。 這與反射無關。
由於這很令人困惑,我會這樣寫:
public class Legacy {
static {
table = new HashMap<String, Legacy>();
A = new Legacy("A");
B = new Legacy("B");
}
public static final Legacy A;
public static final Legacy B;
private String type0;
private static Map<String, Legacy> table;
private Legacy(String id) {
type0 = id;
table.put(type0, this);
}
public static void main(String[] args) throws Exception {
Field f1 = Legacy.class.getDeclaredField("A");
Object o = f1.get(null);
}
}
這樣,即使成員更改位置(由於重構,行對齊等),代碼也將始終有效。
我試過這個,因為我看不出你的例子有什么問題。 如果我重新排序聲明,它就有用了:
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Legacy {
private String type0;
private static Map< String, Legacy > table = new HashMap< String, Legacy >();
private Legacy( String id ) {
type0 = id;
table.put( type0, this );
}
public static final Legacy A = new Legacy( "A" );
public static final Legacy B = new Legacy( "B" );
public static void main( String[] args ) throws Exception {
Field f1 = Legacy.class.getDeclaredField( "A" );
Object o = f1.get( null );
}
}
靜態聲明需要(前面)構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.