Usage of annotations (Annotation) in JDK5.0

Source: Internet
Author: User
Tags date define definition comments final interface printf reflection

Many APIs require a significant amount of boilerplate code, for example, in order to write a JAX-RPC Web service, you need to provide an interface and an implementation class. If this program has been annotated annotations to show that the method needs to be invoked remotely, then we can use a tool to automatically generate these boilerplate code.



There are also some APIs that need to maintain some files in the program code, such as JavaBean need a BeanInfo class, EJB needs a deployment description file. It would be more convenient and less likely to make mistakes if we were able to maintain the content of these additional maintenance files in a annotation manner and code.



The Java platform already has a number of special annotation mechanisms. For example, the transient modifier is a special annotation indicating that the field should be ignored by the serialized subsystem; @deprecated Javadoc tag is a special label to show that a method is no longer in use. JDK5.0 provides a feature that lets us define our own annotations, this feature includes how to define the syntax of annotation types, declare the syntax of annotations, read the annotations API, and save annotations with a class file: Annotations can be viewed as a class, we need to save our own defined annotation source code with a. java file, and a note The tools of the release process.



Annotations do not affect the semantics of your code, but they affect the semantics of the programs that are used to process tools that contain annotated program code so that they (tools) can affect the running state. Comments can be read from the source code, read from the compiled. class file, or read at run time through the reflection mechanism.



Annotations are a complement to javadoc tagging. In general, if our primary goal is to influence or produce documents, then we should use Javadoc; otherwise, we should use the annotation annotations.



General application developers may never need to define an annotation type, but it is not complicated to define our own annotation types. Annotation type definition is similar to defining an interface, we need to precede this keyword with an @ symbol in interface. Each method in the annotation defines an element of this annotation type, which must not contain parameters or throw exceptions in the declaration of the method, and the return value of the method is limited to simple types, String, Class, Emnus, annotations, and arrays of these types. Method can have a default value. Here is an example of annotation type definition:

/*** describes the Request-for-enhancement (RFE) that led* to the presence of of the "API annotated @interface    requestforenhancement {int id ();    String Synopsis ();     String engineer () default "[Unassigned]";    String date (); Default "[unimplemented]"; }



Once you have defined an annotation type, you can use it as an annotation statement. Note A special modifier that can be used wherever other modifiers (such as public,static, or final, etc.) are used. By convention, comments should be placed before other modifiers. The annotation's declaration follows the name of the annotation type followed by the @ symbol followed by the parentheses, which lists the key-value pairs of elements/methods in the annotation. Value must be a constant. Here is an example of using the annotation type defined above:




@RequestForEnhancement (



id = 2868724,



Synopsis = "Enable Time-travel",



Engineer = "Mr Peabody",



Date = "4/1/3007"



)



public static void Travelthroughtime (Date destination) {...}








Comments with no elements/methods are become tag (marker) annotation types, such as








/**



* Indicates that the specification of the annotated API element



* is preliminary and subject to change.



*/



Public @interface Preliminary {}








When you use a tag annotation, the parentheses behind it can be omitted, for example:








@Preliminary public class Timetravel {...}








If the annotation contains only one element, the name of the element should be value, for example:








/**

* Associates A copyright notice with the annotated API element.

*/

Public @interface Copyright {String value ();}






If the element's name is value, when using this annotation, the element's name and equal sign can be omitted, such as:








@Copyright ("2002 Yoyodyne Propulsion Systems")

public class Oscillationoverthruster {...}






To combine the things mentioned above, we created a simple annotation based test framework. First we need a tag annotation type to illustrate that a method is a test method and executed by the test tool.








Import java.lang.annotation.*;







/**



* Indicates that this annotated method is a test method.



* This annotation should is used only on parameterless static methods.



*/



@Retention (Retentionpolicy.runtime)



@Target (Elementtype.method)



Public @interface Test {}








We can note that this annotation type is also annotated in the province, which is called meta annotation. The first comment (@Retention (retentionpolicy.runtime)) indicates that this type of annotation is reserved by the VM so that it can be read at run time through reflection; the second annotation @target (Elementtype.method) Indicates that this annotation can only be used to annotate methods.







Here is a simple class where several of the methods are added to the comment above:








public class Foo {



@Test public static void M1 () {}



public static void M2 () {}



@Test public static void M3 () {



throw new RuntimeException ("Boom");



}



public static void M4 () {}



@Test public static void M5 () {}



public static void M6 () {}



@Test public static void M7 () {



throw new RuntimeException ("Crash");



}



public static void M8 () {}



}








Here is the test tool:








Import java.lang.reflect.*;







public class Runtests {



public static void Main (string[] args) throws Exception {



int passed = 0, failed = 0;



For (Method M:class.forname (Args[0]). GetMethods ()) {



if (M.isannotationpresent (Test.class)) {



try {



M.invoke (NULL);



passed++;



catch (Throwable ex) {



System.out.printf ("Test%s failed:%s%n", M, Ex.getcause ());



failed++;



}



}



}



System.out.printf ("Passed:%d, Failed%d%n", passed, Failed);



}



}








The tool iterates through all the methods in the class using a class masterpiece as a parameter, and invokes the method in which the @test annotation is added. If a method throws an exception, the test fails, and the final test results are printed. The following is the result of the program running:








$ java runtests Foo



Test public static void foo.m3 () failed:java.lang.RuntimeException:Boom



Test public static void Foo.m7 () failed:java.lang.RuntimeException:Crash



Passed:2, Failed 2












Although this test tool is just a toy, he shows the powerful features of the annotation.




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.