Skip to content

Instantly share code, notes, and snippets.

@penglongli
Last active May 14, 2017 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penglongli/d39f0221050051e47c087b05f782dcb7 to your computer and use it in GitHub Desktop.
Save penglongli/d39f0221050051e47c087b05f782dcb7 to your computer and use it in GitHub Desktop.
[java] Use reflection to add annotation to the entity class(为实体类添加 Annotation 注解)
public class AnnotationUtils {
/**
* Add annotation to the entity class
* @param clazz Entity's class
* @param annotationClazz Annotation's class
* @param annotation New Annotation
*/
public static void addAnnotation(Class clazz, Class annotationClazz, Annotation annotation) {
clazz.getAnnotations();
try {
Field field = Class.class.getDeclaredField("annotationData");
field.setAccessible(true);
Object object = field.get(clazz);
field = object.getClass().getDeclaredField("annotations");
field.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(object);
annotations.put(annotationClazz, annotation);
} catch (IllegalAccessException | NoSuchFieldException e) {
System.out.println("AnnotationUtils: add annotation failed!");
}
}
}
public class TestAnnotation {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Annotation newAnnotation = new Something() {
@Override
public String someProperty() {
return "another value";
}
@Override
public short replicas() {
return 0;
}
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
};
AnnotationUtils.addAnnotation(Foobar.class, Something.class, newAnnotation);
Something something = (Something) Foobar.class.getAnnotations()[0];
System.out.println(something.someProperty());
}
@Something(someProperty = "some value")
public static class Foobar {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Something {
String someProperty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment