Java annotation syntax

Source: Internet
Author: User
Java has provided the annotation (annotation) function since j2se5. The annotation of Java can be attached to packages, classes, methods, and fields, which is equivalent to adding additional auxiliary information to them. Annotation attached to package, class, method, field, etc. If there is no external parsing tool to parse and process it, it will not Source code Or class.

However, external tools such as javac and EJB containers can be used to parse annotation attached to package, class, method, and field, and process annotation accordingly, for example, changing the behavior of objects/methods during running.

Java standard Annotation

@ Deprecated is equivalent to @ deprecated of javadoc. It is not recommended to specify the object class and method marked by @ deprecated. It is mainly used for compiling tools such as javac.

@ Override indicates that the object method reloads the method of the parent class. During compilation, compilation tools such as javac will determine whether the overload method is correct based on this annotation.

@ Suppresswarnings tells javac and other compilers to ignore the specified warning information.

@ Target the defined annotation can be attached to those objects.

@ Retention annotation.

Use of java standard Annotation

@ Deprecated:

@ Deprecated

Public class testbean {

...

}

@ Suppresswarnings:

@ Suppresswarnings ("serial ")

Public class testbean implements java. Io. serializable {

...

}

@ Suppresswarnings (value = {"serial", "unchecked "})

Public String dosomething (){

...

}

@ Override:

@ Override

Public String dosomething (){

...

}

Annotation Definition

Definition method:

@ Interface annotation name {definition body}

Definition Example 1:

Public @ interface myannotation {}

This example defines an annotation without any attributes/methods.

Example 2:

Public @ interface myannotation {

Public String Value ();

}

This example defines Annotation with only one method as value. Generally, there is only one annotation method, and the method name must be defined as value.

Example 3:

@ Retention (retentionpolicy. runtime)

@ Target (elementtype. Method)

Public @ interface myannotation {

Public String Value ();

Public String [] multivalues ();

Int number () default 0;



}

This example defines an annotation with multiple methods. Set the default value of one method number to 0. The multivalues method is defined as an array. The annotation definition can be modified using metaannotation. Metaannotation has the following two:

@ Retention

@ Target

@ Retention and @ target are described below.

@ Retention

@ Retention can be set to a value of the retentionpolicy type.

Example:

@ Retention (retentionpolicy. runtime)

Retentionpolicy value description

Retentionpolicy. Class annotation information will be stored in the class file during compilation by the compiler, but will not be loaded in the VM during execution. That is to say, the annotation information cannot be dynamically obtained during execution. If @ retention is not set, this will be the default value.

Retentionpolicy. runtime annotation information will be stored in the class file during compilation by the compiler, and will be loaded by the VM during execution.

Retentionpolicy. Source annotation information will be discarded by the compiler during compilation.

@ Target

@ Target indicates the Java element to which annotation can be attached and can be set to a value of the Java. Lang. annotation. elementtype array type.

Example 1:

@ Target (elementtype. Method)

Example 2:

@ Target (value = {elementtype. constructor, elementtype. Field, elementtype. local_variable, elementtype. Method })

Elementtype is an enumeration type with the following definitions:

Elementtype value description

Elementtype. annotation_type is applied to the meta annotation of other annotations.

Elementtype. constructor Constructor

Elementtype. Field field

The local variable in the elementtype. local_variable Method

Elementtype. Method

Elementtype. Package package

Parameters of elementtype. Parameter Method

Elementtype. Type class, interface or enumeration Declaration

Custom Java Annotation

Annotation is a special interface. Therefore, you can define methods and attributes in annotation, or inherit a class from annotation (implements ).

The following is a simple example. Let's learn more about Annotation step by step.

No method/attribute annotation example:

Myannotation0.java

Package com. Test. annotation;

Public @ interface myannotation0 {



}

Myannotation0 is an annotation without any methods and attributes.

Use myannotation0:

Testmyannotation0.java

@ Myannotation0

Public class testmyannotation0 {

@ Myannotation0

Public void testmethod (){

}

}

There is a value method annotation example:

Myannotation1.java

Public @ interface myannotation1 {



/**

* Value Method

* @ Return Value

*/

Public String Value ();

}

Myannotation1 has a method named value.

Myannotation1 usage:

Testmyannotation1.java

@ Myannotation1 ("hello ")

Public class testmyannotation1 {

@ Myannotation1 (value = "world ")

Public void testmethod (){

}

}

You can use the @ annotation name (method name 1 = value 1, method name 2 = value 2,
...) To assign a value to annotation. When there is only one method, it can be omitted as: @ annotation name (value 1)
. When the method returns an array, you can use the method name = {value 1, value 2 ,...} Assign a value to it.

There is a value method and an annotation attribute example:

If necessary, you can also define attributes for annotation. As follows:

Myannotation2.java

@ Interface myannotation2 {

Public String Value ();

Public String myproperty = "Hello World ";

}

Among them, myproperty can only be declared as public or non-public (public by default when there is no public modifier) is static, final attribute (even if not written, static, final by default ).

Example:

Testmyannotation2

Class testmyannotation2 {

Public static void main (string [] ARGs ){

System. Out. println (myannotation2.myproperty );

}

@ Myannotation2 ("")

Public void testmethod1 (){

}

}

Printed at the meeting:

Hello World

Definition and use of simplified Annotation

This section describes the definition and use of complex annotation.

First lookCode:

Myannotation3.java

Public @ interface myannotation3 {

Public String Value ();

Public String [] multivalues ();

Int number () default 0;

}

Myannotation3 has a multivalues method that returns string [], and a number method that returns Int. The number method has the default value 0.

Example:

Testmyannotation3.java

Class testmyannotation3 {

@ Myannotation3 (value = "Call testmethod1", multivalues = {"1", "2"}, number = 1)

Public void testmethod1 (){

}

@ Myannotation3 (value = "Call testmethod2", multivalues = {"1", "2 "})

Public void testmethod2 (){

}

}

Number has a default value. Therefore, you can leave it unspecified when marking. Other methods must be assigned values through the method described above. Multivalues returns a string [] array, so you can assign values to it through multivalues = {"1", "2.

In this case, what role does annotation play?

1. Compilation tools or other tools can automatically generate configuration files, documents, and other external files based on the annotation information attached to the code.

For example, Sun provides apt (annotation processing tool)
Tool, APT tool is a command line tool that can process annotation. APT provides source code-level resolution during the compilation period, and can generate new source code and other files during parsing.
And can also compile the generated source code.

2. OthersProgramThe annotation information of the program to be executed can be dynamically parsed at runtime, and different operations can be performed according to the appended annotation information.

For example, the ejb3 specification widely uses the Annotation Feature. For example, the EJB container will
Register the pojo as a stateless session based on this Annotation
Bean. Ejb3 uses annotation to greatly simplify the EJB development and configuration process. We willArticleSpecifically introduce EJB
The principle and usage of annotation are not described here.

This article uses a simple example to illustrate how to dynamically parse annotation at runtime. We will introduce the apt tool in other recent articles.

For example, we have defined myannotation3 annotation:

Myannotation3.java

Package com. Test. annotation;

Import java. Lang. annotation. annotation;

Import java. Lang. annotation. inherited;

Import java. Lang. annotation. retention;

Import java. Lang. annotation. retentionpolicy;

@ Retention (retentionpolicy. runtime)

Public @ interface myannotation3 {

Public String Value ();

Public String [] multivalues ();

Int number () default 0;

}

A comment named myannotation3 is defined above.

Let's define another getmyannotation class, which uses myannotation3 annotation:

Getmyannotation. Java:

Package com. Test. annotation. test;

Import java. Lang. annotation. annotation;

Import java. Lang. Reflect. field;

Import java. Lang. Reflect. method;

Import javax. EJB. EJB;

Import javax. Naming. initialcontext;

Import javax. Naming. namingexception;

Import com. Test. annotation. myannotation3;

// Append the myannotation3 annotation to the getmyannotation class

@ Myannotation3 (value = "class getmyannotation", multivalues = {"1", "2 "})

Public class getmyannotation {

// Append the myannotation3 annotation to the testfield1 attribute

@ Myannotation3 (value = "Call testfield1", multivalues = {"1"}, number = 1)

Private string testfield1;

// Append the myannotation3 annotation to the testmethod1 Method

@ Myannotation3 (value = "Call testmethod1", multivalues = {"1", "2"}, number = 1)

Public void testmethod1 (){

}

@ Deprecated

@ Myannotation3 (value = "Call testmethod2", multivalues = {"3", "4", "5 "})

Public void testmethod2 (){

}

}

In the above example, getmyannotation is very simple and does not have any functions in it. However, the myannotation3 annotations are added for class, field, and method declarations.

Next we will use the program testmyannotation3 to parse the myannotation3 annotation in getmyannotation.

Annotation parsing during runtime

Testmyannotation3.java

Public class testmyannotation3 {

Public static void main (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: 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: Methods ){

System. Out. println ("[getmyannotation." + method. getname () + "]. annotation :");

If (method. isannotationpresent (myannotation3.class )){

Myannotation3 methodannotation = method. getannotation (myannotation3.class );

Printmyannotation3 (methodannotation );

}

}

}



Private Static void printmyannotation3 (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 getmyannotation
multivalues =, 1, 2
Number = 0}
-- fields annotations --
[getmyannotation. testfield1]. annotation:
{value = call testfield1
multivalues =, 1
Number = 1}
-- Methods annotations --
[getmyannotation. testmethod1]. annotation:
{value = call testmethod1
multivalues =, 1, 2
Number = 1}
[getmyannotation. testmethod2]. annotation:
{value = call testmethod2
multivalues =, 3,4, 5
Number = 0}

Interfaces related to annotation provided by JDK and later versions:

Interface java. Lang. Reflect. annotatedelement {

Boolean isannotationpresent (class <? Extends annotation> annotationclass );

<T extends annotation> T getannotation (class <t> annotationclass );

Annotation [] getannotations ();

Annotation [] getdeclaredannotations ();

}

This interface is used to obtain annotation information attached to classes, constructor, field, method, and package.

Jdk1.5 has implemented the annotatedelement interface for several classes related to this:

Java. Lang. Reflect. accessibleobject,

Java. Lang. Reflect. Class,

Java. Lang. Reflect. constructor,

Java. Lang. Reflect. Field,

Java. Lang. Reflect. method,

Java. Lang. Reflect. Package

Therefore, the reflection function can be used to dynamically parse the attached annotation information in the program.

Summary:

This article provides an example to illustrate how to dynamically parse annotation. You can use the Annotation Feature of Java to complete more complex functions.

 

Trackback: http://yelinsen.iteye.com/blog/1051886

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.