问题:今天项目有一个需求,需要new一个HashMap,将它赋值给一个修饰符为static+final的Map。
思路:不能停服,那就只能动态修改了,那必然用到反射。反射的一些基础知识请自行学习
代码:
1 /**
2 * 修改静态final字段的值
3 * @author chenzl
4 * 2015-09-22
5 */
6 public classSetFinalValue {
7
8 public static final Map openMap = new HashMap();
9
10 public static void main(String[] args) throwsException {
11 Field target = SetFinalValue.class.getField("openMap");
12
13 int modify =target.getModifiers();
14 SetFinalValue.checkModifier(modify);
15
16 Map openMap2 = new HashMap();
17 openMap2.put(2, "abcde");
18 try{
19 //取消 Java 语言访问检查,详细查看 API(这里可以不写)
20 target.setAccessible(true);
21
22 //获得修饰符Field对象,通过这个对象可以对另