我现在有一个类:
public class AccountCache {
private AccountCache() {
}
private static final HashMap<String,Account> map=new HashMap<String, Account>();
}
我想从其他类了,利用反射获取map里内存中的数据。private 构造和属性是不能直接调用的,java提供了反射机制,可以利用反射来获取里面的值:
Class c = AccountCache.class;
//调用私有构造
Constructor c0=c.getDeclaredConstructor();
c0.setAccessible(true);
AccountCache po=(AccountCache)c0.newInstance();
//访问私有属性
Field f= c.getDeclaredField("map");
f.setAccessible(true);
Object value=f.get(po);
HashMap<String,Account> map=( HashMap<String,Account> )value;
//打印一下
System.out.println(value);