JDK5.0 ANNOTATION

xiaoxiao2021-03-06  15

Many APIs require a considerable number of template 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 added annotations to illustrate that method needs to be called remotely, then we can automatically generate these template code a tool.

There are also some APIs to maintain some files in the program code, such as JavaBean requires a BeanInfo class, and EJB requires a deployment description file. If we are able to put these questions about the other maintenance of files to comment Annotation and the code will be more convenient to reduce the opportunity to reduce errors.

The Java platform has some mechanisms for special annotations. For example, Transient modifiers are a special annotation that this field should be ignored by the serialization subsystem; the @DepRecated JavaDoc label is a special tag to indicate that a method is no longer used. JDK5.0 provides a feature that lets us define our own comments. This feature contains how to define the syntax of the comment type, the grammar of the annotation, read the annotation of the API, a class file save annotation (Translator Note: It is seen as a class, we need to use a .java file to save our own notes source code) and a tool for annotation.

The comment does not affect the semantics of the code, but it affects the processing of tools for processing tools that contain comments, so that they can affect the semantics of the running state. Note You can read from the source code, read from the compiled .class file, can also be read at runtime by reflective mechanism.

The comment is a supplement to the Javadoc tag. Under normal circumstances, if our main goal is an influence or a document, then we should use javadoc; otherwise, we should use annotations.

The general application developers may never need to define a comment type, but it is not complicated to define our own annotation type. Note Type Definition Fly, one interface is similar, we need to add an @ symbol in front of the keyword of Interface. Each method in the comment defines an element of this comment type. In the declaration of the method in the comment, it must not contain parameters, nor will it throw an exception; the return value of the method is limited to simple type, string, clas, emnus, notes, And the arrays of these types. The method can have a default. Here is an example of a comment type definition:

/ *** Describes the Request-For-Enhancement (RFE) that led * to the presence of the annotated API element * / public @interface RequestForEnhancement {int id ();. String synopsis (); String engineer () default "[ Unassigned] "; string Date (); default" [unimplement] ";

Once a comment type is defined, you can use an annotation declaration. Note One Special modifier is used in other modes (such as public, static, or final, etc.). According to conventions, comments should be placed in front of other modes. Note The statement follows the name of this comment type with the @ symbol, then followed by brackets, and the key-value pairs of the element / method in this comment are listed in parentheses. The value must be constant. Here is an example, 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) {...}

Note without element / method is a marker annotation type, for example

/ **

* INDICES That The Specification of the Annotated API Element

* Is preliminary and subject to change.

* /

Public @Interface preliminary {}

When the marker comment is used, the brackets thereof can be omitted, for example:

@Preliminary Public Class Timetravel {...}

If only one element is included in the comment, the name of this element should be Value, for example:

/ ** * Associates a copyright notice with the annotated api element. * / Public @ITERface Copyright {string value ();

If the name of the element is Value, when using this comment, the name and equivalent of the elements can be omitted, such as:

@Copyright ("2002 yoyodyne propulsion systems) public class oscillationOverthruster {...}

In order to combine the above mentioned things, we created a simple note-based test framework.

First we need a tag

The annotation type is used to illustrate a method of testing and is executed by the test tool.

Import java.lang.annotation. *;

/ **

* Indeicates what the annotated method is a test method.

* This Annotation SHOULD BE Used Only On Parameterless Static Methods.

* /

@ReTENTION (RETENTIONPOLICY.RUNTIME)

@Target (ElementType.Method)

Public @Iterface test {}

We can notice that this annotation is also annotated, this annotation is called a meta-note. The first annotation (@RetrionPolicy.Runtime) means that this type of comment is reserved by the VM to make it read by reflecting during runtime; the second annotation @Target (ElementType.Method) means that this comment can only Used to comment.

Here is a simple class, where several methods are added 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, FAILEDs;

}

}

This tool uses a class name as a parameter, traverses all the methods in this class, and calls the method of being added to the @Test annotation. If a method throws an exception, then this test has failed, and the final test result is printed. Below is the result of the program run:

$ Java Runteests 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

转载请注明原文地址:https://www.9cbs.com/read-45356.html

New Post(0)