Java Custom Annotations

Source: Internet
Author: User

Custom annotations:

Use the @interface modifier to define the annotation class, and you cannot inherit other annotations or interfaces when defining annotations. Each of the methods in the annotation class actually declares a configuration parameter, and no arguments are thrown without an exception. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be base type, Class, String, enum). You can declare the default value of a parameter through default.

  To define the annotation format:
Public @interface annotation name {definition body}

  Supported data types for annotation parameters:

1. All basic data Types (Int,float,boolean,byte,double,char,long,short)
2.String type
3.Class type
4.enum type
5.Annotation type
6. Arrays of all types above

How to set the parameters of the annotation type:
First, it can only be decorated with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string,enum,class,annotations data types, As well as these types of arrays. For example, String value (), where the parameter member is string;
Third, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses.

Java provides four meta-annotations, which are responsible for explaining the annotation.

@Target:

@Target illustrates the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Target can be more clearly decorated by using target in the declaration of the annotation type.

  Function: Used to describe the scope of use of annotations (i.e., where the annotations described can be used)

 The values (ElementType) are:

1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the domain
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

@Retention:

 @Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.

  Function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the annotation being described is valid)

 The values (Retentionpoicy) are:

1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)

The Retention meta-annotation type has a unique value as a member, and its value is derived from the enumeration type value of Java.lang.annotation.RetentionPolicy.

@Inherited:

  @Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

The reflection API enhances this inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime. If we use Java.lang.reflect to query the annotation of a @inherited annotation type, the reflection code check will work: Examine the class and its parent class until the specified annotation type is found, or reach the top level of the class inheritance structure.

@Documented:

  @ Documented is used to describe other types of annotation that should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.

How to read annotations--annotations on a class

---------------------------------------------

Java code
// gets the specified annotation  on the class Annotation Annotation = class.class. Getannotation (Myannotation.  Class);     // gets all annotations on the class, including the inherited annotations.   annotation[] annotations = class.class. getannotations ();     // takes all annotations on the current class, excluding inherited   annotation[] annotations = class.class. Getdeclaredannotations ();  

How to read annotations--Annotations on methods

Method m=. Class. GetMethod (String name, class<?>... parametertypes); // or get all the methods // methods[] methods= class. Class.getmethods (); // gets the specified annotation  on the method Annotation Annotation = m.getannotation (myannotation.  Class);     // gets all the annotations on the method, including the inherited annotations.   annotation[] Annotations = m.getannotations ();     // all annotations on the current method are taken, excluding the  inherited annotation[] annotations = m.getdeclaredannotations ();  

Custom annotation Classes:

@Inherited @retention (retentionpolicy.runtime)  public @Interface  myannotation{    default "";}

Parent class:

@MyAnnotation (Annotations on Value= "class names") Public Abstract classParentClass {@MyAnnotation (value= "Abstractmethod method for parent class")       Public Abstract voidAbstractmethod (); @MyAnnotation (Value= "Doextends method for parent class")       Public voiddoextends () {System.out.println ("ParentClass doextends ..."); } @MyAnnotation (Value= "Dohandle method for parent class")       Public voidDohandle () {System.out.println ("ParentClass dohandle ..."); }  }

Sub-class:

 Public classChildClassextendsparentclass{//the subclass implements the abstract method of the parent class@Override Public voidAbstractmethod () {System.out.println ("Subclass implements the Abstractmethod abstract method of the parent class"); }              //subclass inherits the Doextends method of the parent class//Dohandle method for subclasses overriding parent classes@Override Public voidDohandle () {System.out.println ("Subclass overrides the Dohandle method of the parent class"); }  }

Test class:

 Public classTesttool { Public Static voidMain (string[] args)throwsnosuchmethodexception, SecurityException {Class<ChildClass> clazz = ChildClass.class; if(Clazz.isannotationpresent (myannotation.class) {myannotation CLA= Clazz.getannotation (myannotation.class); System.out.println ("Subclass inherits the annotation on the parent class class with the following information:" +Cla.value ()); } Else{System.out.println ("Subclass does not inherit to parent class annotation"); }        //implementing an abstract method testmethod = Clazz.getmethod ("Abstractmethod",Newclass[]{}); if(Method.isannotationpresent (myannotation.class) ) {myannotation ma= Method.getannotation (myannotation.class); System.out. println (The subclass implements the Abstractmethod abstract method of the parent class, inheriting the annotation in the parent class abstract method, with the following information: "+Ma.value ()); } Else{System.out. println ("Subclasses implement the Abstractmethod abstract method of the parent class and do not inherit the annotation in the parent class abstract method"); }        //Overlay TestMethod methodoverride = Clazz.getmethod ("Doextends",Newclass[] {}); if(Methodoverride.isannotationpresent (myannotation.class) ) {myannotation ma= Methodoverride.getannotation (myannotation.class); System.out. println (The subclass inherits the Doextends method of the parent class, inherits the annotation in the parent class Doextends method, with the following information: "+Ma.value ()); } Else{System.out. println ("Subclass inherits the Doextends method of the parent class and does not inherit the annotation in the parent class Doextends method"); }        //Inherit TestMethod method3 = Clazz.getmethod ("Dohandle",Newclass[] {}); if(Method3.isannotationpresent (myannotation.class) ) {myannotation ma= Method3.getannotation (myannotation.class); System.out. println (The subclass overrides the Dohandle method of the parent class, inheriting the annotation in the parent class Dohandle method, with the following information: "+Ma.value ()); } Else{System.out. println ("The subclass overrides the Dohandle method of the parent class and does not inherit the annotation in the parent class Dohandle method"); }    }}

The output results are as follows:

Subclasses inherit the annotation on the parent class class with the following information: Annotations on class names
Subclasses implement the Abstractmethod abstract method of the parent class and do not inherit the annotation from the parent class abstract method
The subclass inherits the Doextends method of the parent class, inheriting the annotation in the parent class Doextends method, with the following information: The Doextends method of the parent class
The subclass overrides the Dohandle method of the parent class and does not inherit from the annotation in the parent class Dohandle method

When the annotation class is @inherit annotated, the test results are as follows:

Subclasses do not inherit to the parent class annotation
Subclasses implement the Abstractmethod abstract method of the parent class and do not inherit the annotation from the parent class abstract method
The subclass inherits the Doextends method of the parent class, inheriting the annotation in the parent class Doextends method, with the following information: The Doextends method of the parent class
The subclass overrides the Dohandle method of the parent class and does not inherit from the annotation in the parent class Dohandle method

Conclusion:

We know that when writing custom annotations, you can specify whether custom annotations can be inherited by specifying @inherited annotations.

The test results show that the @Inherited can only control whether annotations on the class name can be inherited. Cannot control whether annotations on a method can be inherited.

Summarize:

1. The description in the JDK documentation is that only annotation applied on the class can be inherited, and the result of the actual application is that the annotation of a method that is not overridden can be inherited, except that the annotation applied on the class can be inherited .

2, note that: When the method is rewritten, annotation will not be inherited.

3, in order to make annotation inherited, need to annotation in the logo @inherited, and if you want to be reflected application, you need to have a @retention (retentionpolicy.runtime) logo.

4. The inheritance of annotation cannot be applied on the interface.

In particular, the spring transaction note @transactional:

@java. Lang.annotation.Target (Value={java.lang.annotation.elementtype.method, Java.lang.annotation.ElementType.TYPE})
@java. Lang.annotation.Retention (Value=java.lang.annotation.retentionpolicy.runtime)
@java. lang.annotation.Inherited
@java. lang.annotation.Documented

@Transactional annotations should only be applied to methods of public visibility.

Java Custom Annotations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.