Modify a class definition's annotation string parameter at runtime

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

    This one works on my machine with Java 8. It changes the value of ignoreUnknown in the annotation @JsonIgnoreProperties(ignoreUnknown = true) from true to false.

    final List<Annotation> matchedAnnotation = Arrays.stream(SomeClass.class.getAnnotations()).filter(annotation -> annotation.annotationType().equals(JsonIgnoreProperties.class)).collect(Collectors.toList());    
    
    final Annotation modifiedAnnotation = new JsonIgnoreProperties() {
        @Override public Class<? extends Annotation> annotationType() {
            return matchedAnnotation.get(0).annotationType();
        }    @Override public String[] value() {
            return new String[0];
        }    @Override public boolean ignoreUnknown() {
            return false;
        }    @Override public boolean allowGetters() {
            return false;
        }    @Override public boolean allowSetters() {
            return false;
        }
    };    
    
    final Method method = Class.class.getDeclaredMethod("getDeclaredAnnotationMap", null);
    method.setAccessible(true);
    final Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) method.invoke(SomeClass.class, null);
    annotations.put(JsonIgnoreProperties.class, modifiedAnnotation);
    
    0 讨论(0)
提交回复
热议问题