And*_*rew 3 java reflection initialization
我没有别的选择,只能通过反射访问一组我无法修改的类.但是,使用下面主方法中显示的方法会抛出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);
}
}
Run Code Online (Sandbox Code Playgroud)
在"反射==不好!!!"之前