Java,用反射设置字段值 [英] Java, set field value with reflection

查看:543
本文介绍了Java,用反射设置字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个不是开源的项目,我需要修改一个或多个类。

Im working with one project which is not opensource and i need to modify one or more its classes.

在一个类中跟随集合:

private Map<Integer, TTP> ttp = new HashMap<>(); 

我需要做的就是使用反射并在这里使用concurrenthashmap。
我试过以下代码,但它不起作用。

all what i need to do is use reflection and use concurrenthashmap here. i've tried following code but it doesnt work.

Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());


推荐答案

希望这是你要做的事情:

Hope this is something what you are trying to do :

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,用反射设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆