Modify a class definition's annotation string parameter at runtime

后端 未结 7 1769
[愿得一人]
[愿得一人] 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:16

    Try this solution for Java 8

    public static void main(String[] args) throws Exception {
        final Something oldAnnotation = (Something) Foobar.class.getAnnotations()[0];
        System.out.println("oldAnnotation = " + oldAnnotation.someProperty());
        Annotation newAnnotation = new Something() {
    
            @Override
            public String someProperty() {
                return "another value";
            }
    
            @Override
            public Class annotationType() {
                return oldAnnotation.annotationType();
            }
        };
        Method method = Class.class.getDeclaredMethod("annotationData", null);
        method.setAccessible(true);
        Object annotationData = method.invoke(getClass(), null);
        Field declaredAnnotations = annotationData.getClass().getDeclaredField("declaredAnnotations");
        declaredAnnotations.setAccessible(true);
        Map, Annotation> annotations = (Map, Annotation>) declaredAnnotations.get(annotationData);
        annotations.put(Something.class, newAnnotation);
    
        Something modifiedAnnotation = (Something) Foobar.class.getAnnotations()[0];
        System.out.println("modifiedAnnotation = " + modifiedAnnotation.someProperty());
    }
    
    @Something(someProperty = "some value")
    public static class Foobar {
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @interface Something {
        String someProperty();
    }
    

提交回复
热议问题