Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Last active May 6, 2018 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twiceyuan/b8b4d952d6fd641e98f68f1e9d327988 to your computer and use it in GitHub Desktop.
Save twiceyuan/b8b4d952d6fd641e98f68f1e9d327988 to your computer and use it in GitHub Desktop.
[运行时修改注解值的方法] Annotation Value modify #Java
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<? extends Annotation> annotationType() {
return oldAnnotation.annotationType();
}
};
Field field = Class.class.getDeclaredField("annotationData");
field.setAccessible(true);
Object object = field.get(Foobar.class);
field = object.getClass().getDeclaredField("annotations");
field.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(object);
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();
}
@lvdelu
Copy link

lvdelu commented Jul 30, 2017

你这是类上的,方法上的怎么解决,类似于以下

@something(value={})
public void metod(ChangeEvent event){
//do something
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment