Java annotation and java annotation principles
Package com. ann. test; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. inherited; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target ({ElementType. METHOD, ElementType. TYPE}) // scope. Note that the initial letter uppercase/** @ Retention defines the lifecycle of the annotation */@ Retention (RetentionPolicy. RUNTIME)/** @ Inherited describes that a labeled type is Inherited. Subclasses of annotation Classes */@ Inherited/* can be documented by tools such as javadoc. Incluented is a tag Annotation with no members.
* Note: When javadoc is generated, no Chinese comments (English comments are correct) */@ Documentedpublic @ interface Description {String value ();}
Create a Person Interface
Package com. ann. test; public interface Person {public void name (); public void age (); @ Deprecated // public void sing ();}
package com.ann.test;@Description("This is class annotation")public class Child implements Person { @Override @Description("This is method1 annotation") public void name() { // TODO Auto-generated method stub } @Override @Description("This is method2 annotation") public void age() { // TODO Auto-generated method stub } @Override @Description("This is method3 annotation") public void sing() { // TODO Auto-generated method stub } }
Package com. ann. test; import java. lang. annotation. annotation; import java. lang. reflect. method;/*** parse annotation: * Get the runtime annotation information on the class, function, or member through reflection, to implement the logic * @ author Administrator **/public class ParseAnn {public static void main (String [] args) {// 1. use the Class loader to load the Class try {Class c = Class. forName ("com. ann. test. child "); // 2. find the c. isAnnotationPresent (Description. class); boolean isExist = c. isAnnotationPresent (Description. class); if (isExist) {// 3. get the annotation instance Description d = (Description) c. getAnnotation (Description. class); System. out. println (d. value ();} else {System. out. println ("not found class annotation");} // 4. locate the annotation Method [] MS = c. getMethods (); // for (Method m: MS) {// boolean isMExist = m. isAnnotationPresent (Description. class); // if (isMExist) {// Description d = (Description) m. getAnnotation (Description. class); // System. out. println (d. value (); // another resolution Method for (Method m: ms) {Annotation [] as = m. getAnnotations (); for (Annotation a: as) {if (a instanceof Description) {Description d = (Description) a; System. out. println (d. value () ;}}} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
For more detailed explanations, please refer to this great god's blog: http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html