annotation definition and use
Annotations are defined as:
public @interface AnnotationName{}
Using annotations
@ AnnotationNamepublicvoidfunc(){}
Java provides 4 meta annotations
@Retention: The stage of the reservation.
@Target: The object of the annotation adornment, can say class, method, member variable, package.
@Documented: Whether it was written by Javadoc.
@Inherited: Whether annotations can be inherited.
Custom annotations
Member variable definitions for annotations:
public @interface AnnotationName{ default"abc"; intdefault33; boolean flag();}
Where the default decoration represents the defaults.
- Note: Annotation modifies classes, methods, and member variables after they do not take effect on their own and do not have any effect on the program. Only tool classes that provide processing for these annotations are useful.
Instance
Defining annotation Classes
import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Testable { booleandefaultfalse; String name();}
A class that is decorated with annotations
Public classFoo { Public Static void M1() {System. out. println ("I am M1"); } @Testable (isskiped =false, name ="Methond2") Public Static void m2() {System. out. println ("I am M2"); } @Testable (name ="Methond3") Public Static void M3() {System. out. println ("I am M3"); } @Testable (isskiped =true, name ="Methond4") Public Static void M4() {System. out. println ("I am M4"); }}
Tool classes for handling annotations
Import java.lang.reflect.*; Public classtestannotation { Public Static void Main(string[] args) throws SecurityException, ClassNotFoundException, Illegalaccessexception, Illegalarg Umentexception, InvocationTargetException { for(Method M:class.forname ("Foo"). GetMethods ()) {if(M.isannotationpresent (Testable.class)) {System. out. Print (M.getname () +"is Annotation element, so invoke result is:"); M.invoke (NULL); }Else{System. out. println (M.getname () +"is not Annotation element"); } } }}
Output:
M1 is notAnnotation ELEMENTM2 isAnnotation element, so invokeresult is: I am M2M3 isAnnotation element, so invokeresult is: I am M3M4 isAnnotation element, so invokeresult is: I am m4wait is notAnnotation elementwait is notAnnotation elementwait is notAnnotation elementequals is notAnnotation elementtostring is notAnnotation Elementhashcode is notAnnotation Elementgetclass is notAnnotation elementNotify is notAnnotation Elementnotifyall is notAnnotation element
Introduction to Java Annotations annotation