1.2.4 Java Annotation Abstract

Source: Internet
Author: User

1.2.4 Java Annotation Abstract

(This article introduces the dependency injection container Spring and the source code analysis of JUnit)

Java Annotation (Annotation)

Java. lang. annotation. AnnotationIs the parent interface of all Java annotations. It has only one method except override/to override the equals (Object), hashCode (), and toString () of the Object.

Class AnnotationType ()

Returns the type of the annotation.
Java. lang. OverrideIs:
@Target(value=METHOD)@Retention(value=SOURCE)public @interface Override{}
Another example is java. lang. FunctionalInterface.
@Documented@Retention(value=RUNTIME)@Target(value=TYPE)public @interface FunctionalInterface......
These examples reflect some basic content of the Annotation: ① define a Annotation, such as public @ interface MyAnnotation. Instead of extends Annotation, @ interface is used. There are some annotations used to modify custom annotations-meta annotation/meta-annotation. For example, in the Override example, @ Target, @ Retention, and @ shortented are followed by parentheses, Name-value pairs separated by commas).

@ TargetDescribe the applicable scenarios/objectives of the modified annotation. The value is limited by java. lang. annotation. ElementType, including ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE, and TYPE_PARAMETER. For example, the Target is applicable to @ Target (value = ANNOTATION_TYPE). If the annotation only has a single attribute member (name-value Pair ), the member name "value =" can be omitted as @ Target (ANNOTATION_TYPE ).

@ RetentionIndicates the retention policy of the modified annotation, Which is enumerated by RetentionPolicy.

SOURCE will only be stored in the program SOURCE code, or is only valid for the compiler, for example, @ Override. Compiler checkBy default or when a CLASS is specified, this annotation is specified to write to the class file, but this information is not loaded into the JVM; RUNTIMEIndicates that Reflection mechanismObtain the annotation.

@ Brief ented indicates that the annotation is reflected in JavaDoc. ② Annotation is used to modify source code elements (class, method, attribute, parameter, local variable, package, and metaannotation ). ③ The use of the annotation has a clear Bottom Line: They cannot affect the execution of program code.. No matter how tags are added or deleted, code execution will not be affected. However, The program can parse the RUNTIME annotation and determine the code behavior..
Example: JUnit4 custom annotation

Org. junit. Test

Org. junit. Ignore @ Target ({ElementType. METHOD, ElementType. TYPE })

@ Before and @ After can only be identified by one method, replacing the setUp and tearDown methods in previous JUnit versions.

Org. junit. BeforeClass @ Target (ElementType. METHOD)

Org. junit. Before @ Target (ElementType. METHOD)

Org. junit. AfterClass @ Target (ElementType. METHOD)

Org. junit. After @ Target (ElementType. METHOD)

Org. junit. runner. RunWith

Org. junit. runners. Suite. SuiteClasses

Org. junit. runners. Parameterized. Parameters


Parse the RUNTIME annotation ① To define a annotation.
package MyTest;import java.lang.annotation.*;@Target(ElementType.METHOD)  @Retention(RetentionPolicy.RUNTIME)  public @interface MyAnnotation{    String value();}
② Annotation usage class
package MyTest;public class HelloWorld {    @MyAnnotation("Test")    public double add(double m,double n){        return m+n;    }    @MyAnnotation("Ignore")    public double add2(double m,double n){        return m+n;    }}
③ Parse the RetentionPolicy. RUNTIME annotation.
Use c to obtain all public methods, obtain the Annotation [] for each method, and find the custom MyAnnotation. If its value () is "Test", (Double) method. invoke (h, 1, 2.0 );
Package MyTest; import java. lang. annotation. *; import java. lang. reflect. *; public class TestHelloWorld {public static void main (String [] args) throws Exception {// use the reflection mechanism Class directly
 C = MyTest. helloWorld. class; HelloWorld h = (HelloWorld) c. newInstance (); Method [] methods = c. getMethods (); for (Method method: methods) {Annotation [] annotations = method. getDeclaredAnnotations (); for (Annotation annotation: annotations) {if (annotation instanceof MyAnnotation) {MyAnnotation myAnnotation = (MyAnnotation) annotation; System. out. println ("value:" + myAnnotation. value (); if (myAnnotation. value (). equals ("Test") {double d = (Double) method. invoke (h, 1, 2.0); System. out. println (d );}}}}}}
Output: value: Test
3.0
Value: Ignore



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.