Java annotation and java annotation principles
What is annotation?
Annotation is a language form, similar to interfaces and enumeration.
Package test. annotation; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; import test. testEnum;/*** annotation example * @ author liujl **/@ Target ({ElementType. METHOD, ElementType. TYPE}) // you can write it on the method or on the class @ Retention (RetentionPolicy. CLASS) // annotation properties, reserved to the runtime .. Java --> javac -->. class -- java --> class Loader loading --> enter "RunTime" public @ interface ITCastAnnotation {String color () default "blue "; // annotation property type -- String type String value (); // a special annotation property type. int [] arrayAttr () default {1, 2, 3} can be left empty by default }; // annotation property type -- array type TestEnum. triffic lamp () default TestEnum. triffic. RED; MetaAnnotation annotationAttr () default @ MetaAnnotation ("lhm"); // annotation attribute type -- annotation type Class clazz () default String. class; // annotation property type -- Class type}
Use your own defined annotation AnnotationTest. java
package test.annotation;@ITCastAnnotation(annotationAttr=@MetaAnnotation(value="fxx") ,value="111",arrayAttr={2,3,4})public class AnnotationTest {public static void main(String[] args)throws Exception {System.runFinalizersOnExit(true);if(AnnotationTest.class.isAnnotationPresent(ITCastAnnotation.class)){ITCastAnnotation ia=AnnotationTest.class.getAnnotation(ITCastAnnotation.class);System.out.println(ia.value());System.out.println(ia.color());int[] arrayAttr=ia.arrayAttr();for(Integer i:arrayAttr){System.out.print(i+" ");}System.out.println();System.out.println(ia.lamp().nextDeng());System.out.println(ia.annotationAttr().value());System.out.println(ia.clazz());}}}
TestEnum. Triffic is an enumeration class. The Code is as follows:
Package test; public class TestEnum {public static void main (String [] args) {Triffic tr = Triffic. GREEN; System. out. println (tr + "the next light is:" + tr. nextDeng ();} public enum Triffic {RED (400) {@ Overridepublic Triffic nextDeng () {return GREEN ;}, GREEN (200) {@ Overridepublic Triffic nextDeng () {return YELLOW ;}, YELLOW (10) {@ Overridepublic Triffic nextDeng () {return RED ;}}; public abstract Triffic nextDeng (); int time; private Triffic (int time) {this. time = time;} public int getTime () {return time;} public String toString () {return this. name () + ":" + this. time ;}}}
MetaAnnotation. java is a custom meta annotation, which exists as an annotation attribute value type in ITCastAnnotation.
Package test. annotation;/*** defines a meta annotation * @ author liujl **/public @ interface MetaAnnotation {String value ();}
Running result:
111
Blue
2 3 4
GREEN: 200.
Fxx
Class java. lang. String