使用反射设置字段值 [英] Set field value with reflection

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

问题描述

我正在处理一个非开源项目,我需要修改其一个或多个类.

I'm working with one project which is not opensource and I need to modify one or more its classes.

在一个班级里有以下收藏:

In one class is following collection:

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

所有我需要做的就是在这里使用反射和并发hashmap. 我已经尝试了以下代码,但是没有用.

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

这篇关于使用反射设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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