Java annotation Annotation Syntax

Source: Internet
Author: User
Tags deprecated

Java starts with a feature named annotation (annotation, callout) from J2SE5. Java annotation, which can be attached to the package,class, method, field, etc., is equivalent to adding additional auxiliary information to them. Attached to the package,class, method, field, etc. annotation, if there is no external parsing tools to parse and deal with the situation, itself will not have any impact on Java source code or class, and will not have any impact on their execution. But with external tools, such as JAVAC,EJB containers, you can attach to the package,class, method, field annotation, can be processed according to annotation, such as changing objects at runtime/the behavior of the method. Java standard annotation@deprecated is equivalent to Javadoc's @deprecated, the object class that is labeled by @deprecated, method, etc. is noted as deprecated. Mainly used for compiling tools such as Javac. @Override indicates that the object method overloads the parent class. Compile tools such as Javac will determine if the overloaded method is correct based on this annotation. @SuppressWarnings tell Javac that the compiler ignores specific warning messages that you specify. @Target defined annotation can be attached to those objects. @Retention the effect of the annotation period. Java Standard annotation Use @deprecated: @Deprecated Public classTestbean {...} @SuppressWarnings: @SuppressWarnings ("Serial") Public classTestbeanImplementsjava.io.Serializable {...} @SuppressWarnings (Value= {"Serial", "unchecked"}) PublicString dosth () {...} @Override: @Override PublicString dosth () {...} Definition method of annotation: @Interfaceannotation name {definition body} definition Example 1: Public@InterfaceMyannotation {} This example defines a property without any/the annotation of the method. Definition Example 2: Public@Interfacemyannotation { PublicString value ();} This example defines a annotation that has only one method as value (). In general, the method name must be defined as value when there is only one method of annotation. Definition Example 3: @Retention (retentionpolicy.runtime) @Target (Elementtype.method) Public@Interfacemyannotation { PublicString value ();  PublicString [] multivalues (); intNumber ()default0; This example defines a annotation with multiple methods. and set one of the methods number to the default value of 0. The Multivalues method defines an array type. Annotation definitions can be decorated with metaannotation (meta-annotations). Metaannotation has the following 2: @Retention @target We will explain @Retention and @target below. @Retention @Retention can be set to a value of type Retentionpolicy. Example: @Retention (retentionpolicy.runtime)

@Target @Target Indicates which Java element annotation can attach to, and can be set to a value of Java.lang.annotation.ElementType array type. Example 1: @Target (elementtype.method) Use Example 2: @Target (value={elementtype.constructor, Elementtype.field, Elementtype.local_variable, Elementtype.method}) ElementType is an enumeration type that has the following definitions:

Custom Java Annotation Annotation is a special kind of interface. So you can define methods, properties in annotation, or let a class inherit from annotation (Implements). Let's start with a simple example to deepen our understanding of annotation in a step-by-step manner. There is no way/Attribute Annotation Example: Myannotation0.java Packagecom.test.annotation; Public@InterfaceMyAnnotation0 {}myannotation0 is a annotation without any methods and properties. Using Myannotation0:testmyannotation0.java@myannotation0 Public classTestMyAnnotation0 {@MyAnnotation0 Public voidTestMethod () {}} has a value method annotation Example: Myannotation1.java Public@InterfaceMyAnnotation1 {/*** Value Method *@returnvalue*/      PublicString value ();} The MyAnnotation1 has a method named value. MyAnnotation1 use: Testmyannotation1.java@myannotation1 ("Hello") Public classTestMyAnnotation1 {@MyAnnotation1 (value= "World")     Public voidTestMethod () {}} can be @annotation by name (method name 1= value 1, method name 2= value 2, ...) In the form of an assignment to annotation. When there is only one method, it can be omitted directly as the @Annotation name (value 1) of the assignment form. When the method returns an array, you can use the method name ={value 1, value 2, ...} Assign a value to it. Has a value method and an attribute annotation example: if necessary, you can also define properties for it in annotation. As follows: myannotation2.java@InterfaceMyAnnotation2 { PublicString value ();  PublicString myproperty = "Hello World";} Where myproperty can only be declared as public or no public adornment (which is also default to public when no public adornment) is static, the final property (even if it is not written and defaults to static,Final). Use Example: TestMyAnnotation2classTestMyAnnotation2 { Public Static voidMain (string[] args) {System.out.println (myannotation2.myproperty); } @MyAnnotation2 ("")     Public voidtestMethod1 () {}}: The definition of Hello World complex annotation and its use this section describes the more complex annotation definitions and uses. First look at the code: Myannotation3.java Public@InterfaceMyAnnotation3 { PublicString value ();  Publicstring[] Multivalues (); intNumber ()default0;} MyAnnotation3 has a value method that returns string, returns the Multivalues method of string[], and a number method that returns INT. Where the number method has a default value of 0. Use Example: Testmyannotation3.javaclassTestMyAnnotation3 {@MyAnnotation3 (value= "Call TestMethod1", multivalues={"1", "2"}, Number = 1)     Public voidtestMethod1 () {} @MyAnnotation3 (value= "Call testMethod2", multivalues={"1", "2"})     Public voidtestMethod2 () {}}number has a default value, so you can not assign a value to it when labeling. The rest of the methods must be assigned by the method described above. Multivalues returns a string[] array, so you can pass multivalues={"1", "2"} to assign a value to it. So what does annotation do? 1, the compiler tool or other tool can automatically generate external files such as configuration files or documents based on annotation information that is appended to the code. For example, Sun offers the APT (Annotation processing tool) tools, the APT tool is a command-line tool that can handle Annotation, and APT provides parsing at the source level at compile time. New source code and other files can be generated at parse time, and the generated source code can also be compiled. 2, other programs can dynamically parse the annotation information in the program that will be executed at runtime and perform different operations based on the appended annotation information. For example, the EJB3 specification uses the annotation feature more broadly. For example, the EJB container registers the Pojo as a stateless session Bean based on this annotation, as long as the Pojo is annotated with a @stateless annotation for the class. EJB3 uses annotation to greatly simplify the development and configuration of EJBS. In other articles, we will introduce the principles and methods of EJB annotation, which are not detailed here. In this paper, a simple example is given to illustrate how to dynamically parse annotation at run time. Use of apt tools we will introduce them in other recent articles. For example, we define the MyAnnotation3 annotation: Myannotation3.java Packagecom.test.annotation;Importjava.lang.annotation.Annotation;Importjava.lang.annotation.Inherited;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy, @Retention (retentionpolicy.runtime) Public@InterfaceMyAnnotation3 { PublicString value ();  Publicstring[] Multivalues (); intNumber ()default0;} A comment named MyAnnotation3 is defined above. We then define a Getmyannotation class that uses the MyAnnotation3 annotation: Getmyannotation.java: Packagecom.test.annotation.test;Importjava.lang.annotation.Annotation;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJavax.ejb.EJB;ImportJavax.naming.InitialContext;Importjavax.naming.NamingException;ImportCom.test.annotation.MyAnnotation3;//attaching MyAnnotation3 Annotations to the Getmyannotation class@MyAnnotation3 (value = "Class getmyannotation", multivalues = {"1", "2"}) Public classgetmyannotation {//attaching MyAnnotation3 Annotations to the TestField1 property@MyAnnotation3 (value = "Call TestField1", multivalues={"1"}, Number = 1)    PrivateString TestField1; //attaching MyAnnotation3 Annotations to the TestMethod1 method@MyAnnotation3 (value = "Call TestMethod1", multivalues={"1", "2"}, Number = 1)     Public voidtestMethod1 () {} @Deprecated @MyAnnotation3 (value= "Call testMethod2", multivalues={"3", "4", "5"})      Public voidtestMethod2 () {}} above example getmyannotation is very simple, there is no function, but the class (class), Attribute (field), methods (method) affirm (append) the MyAnnotation3 comment. Below we use the program TestMyAnnotation3 to parse the MyAnnotation3 annotation in getmyannotation. Run-time parsing annotation Testmyannotation3.java Public classTestMyAnnotation3 { Public Static voidMain (string[] args) {System.out.println ("--class annotations--"); if(Getmyannotation.class. isannotationpresent (MyAnnotation3.class) {System.out.println ("[Getmyannotation].annotation:"); MyAnnotation3 classannotation= Getmyannotation.class. getannotation (MyAnnotation3.class );        PrintMyAnnotation3 (classannotation); } System.out.println ("--fields annotations--"); Field [] fields= Getmyannotation.class. Getdeclaredfields ();  for(Field field:fields) {if(Field.isannotationpresent (MyAnnotation3.class) {System.out.println ("[Getmyannotation." + field.getname () + "].annotation:"); MyAnnotation3 fieldannotation= Field.getannotation (MyAnnotation3.class );            PrintMyAnnotation3 (fieldannotation); }} System.out.println ("--methods annotations--"); Method[] Methods= Getmyannotation.class. Getdeclaredmethods ();  for(Method method:methods) {System.out.println ("[Getmyannotation." + method.getname () + "].annotation:"); if(Method.isannotationpresent (MyAnnotation3.class) {MyAnnotation3 methodannotation= Method.getannotation (MyAnnotation3.class );              PrintMyAnnotation3 (methodannotation); }        }    }        Private Static voidPrintMyAnnotation3 (MyAnnotation3 annotation3) {if(Annotation3 = =NULL ) {            return; } System.out.println ("{value=" +Annotation3.value ()); String multivalues= "";  for(String value:annotation3.multiValues ()) {multivalues+= ", " +value; } System.out.println ("Multivalues=" +multivalues); System.out.println ("Number=" + annotation3.number () + "}"); }} Output:--class annotations--[Getmyannotation].annotation:{value=Class getmyannotationmultivalues=,1,2 Number=0}--fields annotations--[Getmyannotation.testfield1].annotation:{value=Call testfield1multivalues=,1 Number=1}--methods annotations--[Getmyannotation.testmethod1].annotation:{value=Call testmethod1multivalues=,1,2 Number=1}[getmyannotation.testmethod2].annotation:{value=Call testmethod2multivalues=,3,4,5 Number=0}jdk1.5 later versions are provided with annotation-related interfaces:Interfacejava.lang.reflect.AnnotatedElement {BooleanIsannotationpresent (class<?extendsAnnotation>Annotationclass); <textendsAnnotation> T getannotation (class<t>Annotationclass);    Annotation[] Getannotations (); Annotation[] Getdeclaredannotations ();} This interface is primarily used to obtain additional classes (class), construction method (constructor), Attribute (field), Method, package ( Package) on the annotation information. JDK1.5 Several classes related to this have implemented the Annotatedelement interface: Java.lang.reflect.AccessibleObject, Java.lang.reflect.Class, Java.lang.reflect.Constructor, Java.lang.reflect.Field, Java.lang.reflect.Method, Java.lang.reflect.Package so you can use the reflection (reflection) function to dynamically parse additional annotation information in the program. Summary: This article by example simply explains how to dynamically parse annotation, we can extrapolate, the use of Java annotation features, to complete more complex functions.
Http://www.cnblogs.com/ansen/articles/2100335.html

Java annotation Annotation Syntax

Related Article

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.