Modify a class definition's annotation string parameter at runtime

后端 未结 7 1893
[愿得一人]
[愿得一人] 2020-11-22 04:55

Imagine there is a class:

@Something(someProperty = \"some value\")
public class Foobar {
    //...
}

Which is already compiled (I cannot c

7条回答
  •  爱一瞬间的悲伤
    2020-11-22 05:01

    i am able to access and modify annotaions in this way in jdk1.8,but not sure why has no effect,

    try {
        Field annotationDataField = myObject.getClass().getClass().getDeclaredField("annotationData");
        annotationDataField.setAccessible(true);
        Field annotationsField = annotationDataField.get(myObject.getClass()).getClass().getDeclaredField("annotations");
        annotationsField.setAccessible(true);
        Map, Annotation> annotations =  (Map, Annotation>) annotationsField.get(annotationDataField.get(myObject.getClass()));
        annotations.put(Something.class, newSomethingValue);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {    
        e.printStackTrace();
    }
    

提交回复
热议问题