无法为私有静态最终地图设置新值

时间:2012-08-08 12:35:54

标签: java reflection

我正在使用方法

   static void setFinalStatic(Field field, Object newValue) throws Exception
   {
      field.setAccessible(true);

      final Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }  

用于更改private static final字段 但是如果字段的类型为Map,则会出现异常

Exception in thread "main" java.lang.IllegalAccessException: Can not set static final java.util.Map field org.hibernate.type.TypeFactory.BASIC_TYPES to java.util.HashMap
    at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:55)
    at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:59)
    at sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl.set(UnsafeQualifiedStaticObjectFieldAccessorImpl.java:59)
    at java.lang.reflect.Field.set(Field.java:657)
    at com.company.tester.Main.setFinalStatic(Main.java:64)  

任何想法?

更多代码

  Field types = TypeFactory.class.getDeclaredField("BASIC_TYPES");
  types.setAccessible(true);
  Map val = (Map) types.get(null);
  Map newMap = new HashMap(val);
  newMap.put(String.class.getName(), new MyType());
  setFinalStatic(TypeFactory.class.getDeclaredField("BASIC_TYPES"), new HashMap());

1 个答案:

答案 0 :(得分:3)

field.setAccessible(true)轮换该字段的所有安全检查。改变其表观修饰符无济于事。还有其他因素阻止了它的运作。

我会尝试更新地图,而不是尝试替换地图。

Field types = TypeFactory.class.getDeclaredField("BASIC_TYPES");
types.setAccessible(true);
Object bt = types.get(null);
Field m = bt.getClass().getDeclaredField("m");
m.setAccessible(true);
Map val = (Map) m.get(bt);
val.put(String.class.getName(), new MyType());