Modify a class definition's annotation string parameter at runtime

后端 未结 7 1874
[愿得一人]
[愿得一人] 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 matchedAnnotation = Arrays.stream(SomeClass.class.getAnnotations()).filter(annotation -> annotation.annotationType().equals(JsonIgnoreProperties.class)).collect(Collectors.toList());    
    
    final Annotation modifiedAnnotation = new JsonIgnoreProperties() {
        @Override public Class 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, Annotation> annotations = (Map, Annotation>) method.invoke(SomeClass.class, null);
    annotations.put(JsonIgnoreProperties.class, modifiedAnnotation);
    

提交回复
热议问题