我正在处理一个非开源项目,我需要修改它的一个或多个类。
在一个类中是以下集合:
private Map<Integer, TTP> ttp = new HashMap<>();
我需要做的就是在这里使用反射并使用concurrenthashmap。 我试过下面的代码,但它不起作用。
Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());
最佳答案
希望这是您正在尝试做的事情:
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private Map ttp = new HashMap();
public void test() {
Field declaredField = null;
try {
declaredField = Test.class.getDeclaredField("ttp");
boolean accessible = declaredField.isAccessible();
declaredField.setAccessible(true);
ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
concHashMap.put("key1", "value1");
declaredField.set(this, concHashMap);
Object value = ttp.get("key1");
System.out.println(value);
declaredField.setAccessible(accessible);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
Test test = new Test();
test.test();
}
}
打印出来:
value1
关于java - 使用反射设置字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094871/