Java custom Annotation to get the Annotation value set by Annotation in the Annotation class
Java annotation mechanism is widely used in various frameworks. Some values can be set in annotations. How can this problem be solved.
To obtain the Annotation value set by Annotation in the Annotation class, that is, traverse the method in the Custom Annotation and reflect the execution method. The result is the corresponding Annotation value.
Java code example:
Package com.doc tor. spring. core; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; import java. lang. reflect. method;/*** get the Annotation value set by Annotation in the Annotation class, that is, traverse the Method in the Custom Annotation, and execute the reflection Method. The result is * corresponding Annotation value. ** For details about how to handle complex annotations, see: {@ code AnnotationUtils} ** @ author doctor ** @ time January 23, 2015 6:15:31 */public class AnnotationPractice {public static void main (String [] args) throws ReflectiveOperationException {MyAnnotation myAnnotation = AnnotationP. class. getAnnotation (MyAnnotation. class); System. out. println (myAnnotation); // output: // @com.doc tor. spring. core. annotationPractice $ MyAnnotation (value = AnnotationP ,// Num = 12, address = [1, 2]) for (Method method: myAnnotation. annotationType (). getDeclaredMethods () {if (! Method. isAccessible () {method. setAccessible (true);} Object invoke = method. invoke (myAnnotation); System. out. println ("invoke methd" + method. getName () + "result:" + invoke); if (invoke. getClass (). isArray () {Object [] temp = (Object []) invoke; for (Object o: temp) {System. out. println (o) ;}}// output: // invoke methd num result: 12 // invoke methd value result: AnnotationP // invoke methd address result: [Ljava. lang. string; @ 74a14482 // 1 // 2} @ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. TYPE) @ Documentedprivate @ interface MyAnnotation {String value () default ""; int num () default 100; String [] address () default {};} @ MyAnnotation (value = "AnnotationP", num = 12, address = {"1", "2"}) private static class AnnotationP {}}