Last active
May 14, 2017 22:12
-
-
Save penglongli/d39f0221050051e47c087b05f782dcb7 to your computer and use it in GitHub Desktop.
[java] Use reflection to add annotation to the entity class(为实体类添加 Annotation 注解)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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