Java,用反射设置字段值

编程入门 行业动态 更新时间:2024-10-23 11:24:36
本文介绍了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,用反射设置字段值

本文发布于:2023-07-30 00:37:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!