Java deep understanding of annotations

Source: Internet
Author: User

Java deep understanding of annotations

I. Application of entry notes

This is often the case

Package Tokyo. hot; public class Demo {public static void main (String [] args) {new Thread (). stop (); // draw a line, which is obviously an outdated method }}
This is an outdated method. At this time, annotations will be used to tell the compiler that I know this is outdated and I like to use it.


@ SuppressWarnings ("deprecation") deprecation, outdated, back-word package Tokyo. hot; public class Demo {@ SuppressWarnings ("deprecation") public static void main (String [] args) {new Thread (). stop ();}}

Note: An annotation is a class.

When you have written a class method before but don't want to use it now, you can add a @ Deprecated on the method to avoid disturbing people using this method. This is

An outdated method

public class Demo {public static void main(String[] args) {Out();}@Deprecatedprivate static void Out() {System.out.println("Hello,World!");}}

HashSet, The equals method needs to be rewritten, but the equals () parameter is of the Object type, but accidentally written into another class, this error is not easy to find, then, the annotation @ Override is used for rewriting.

new Thread(new Runnable() {@Overridepublic int run() {}}).start();

Annotation, which is equivalent to a tag. It is added to the package, class, method, variable, field, and so on, telling the compiler that you take the corresponding action according to my tag


OK, annotation of the Fur, already understand!

Ii. annotation definition and reflection call

If we want to use a class, we must first design and write the class, so is the annotation. If we want to use an annotation, we must also design and write the annotation in advance.

1. Define annotation classes:

Public @ interface MyTokyo {} is the same as defining an interface.


2. The annotation class is applied:
@ MyTokyo
Class MyClass {}, check whether this annotation exists in this class

3. Reflection on the "Application annotation class"
Reflection must be used to check a class.

@ MyTokyopublic class Demo {public static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); // check whether there is any annotation if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo );}}}

You will find that nothing is printed.
Add annotation, annotation> source Annotation on custom Annotation

@ Retention (RetentionPolicy. RUNTIME)
Public @ interface MyTokyo {}

@ Retention (RetentionPolicy. RUNTIME) indicates that the compiler retains the custom annotation to the RUNTIME, because the custom annotation may be in the compilation phase,
After javac compiles the source file into a class, the annotation of the source program may be removed, and whether the annotation of the class is retained when the class loader loads the class into the memory,
It is also a problem.

Note: The content in the class file is not a bytecode. Only after the class loader performs security checks on the class file and other operations, the binary data loaded into the memory is the bytecode.

The life cycle of an annotation has three stages:
1. java source file 2. class file 3. bytecode in memory

Therefore, @ Retention has three values:

(RetentionPolicy. SOURCE file phase)

(RetentionPolicy. CLASS class file stage)

(RetentionPolicy. RUNTIME stage)

The default value is the CLASS stage.

@ Override the default value is (etentionPolicy. SOURCE file phase)

@ SuppressWarnings the default value is (etentionPolicy. SOURCE file phase)

@ Deprecated default value (RetentionPolicy. RUNTIME stage)


Continue. Add an annotation @ Target to the automatic annotation.

@ Retention (RetentionPolicy. SOURCE)
@ Target (ElementType. METHOD)
Public @ interface MyTokyo {}

Purpose: Tell the compiler that a custom annotation can only load methods.

Both classes and methods can be used.
@ Retention (RetentionPolicy. SOURCE)

@ Target ({ElementType. METHOD, ElementType. TYPE })

Public @ interface MyTokyo {}


Note that it is TYPE, TYPE, not only class, but also interface, so it is more appropriate to use TYPE instead of class.


3. Add attributes for annotations


Annotation is powerful because of its attributes.

The annotation misses the interface, and the annotation attributes are similar to the method.

@ Retention (RetentionPolicy. RUNTIME) @ Target ({ElementType. METHOD, ElementType. TYPE}) public @ interface MyTokyo {String color (); // The annotation has an attribute color and returns a String}

The main function can be used to set the attribute value.

@ MyTokyo (color = "red") public class Demo {public static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); // check whether there is any annotation if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo. color ());}}}

Print red. This is to add an attribute for the annotation. When used, set the attribute value for it.

@ Retention (RetentionPolicy. RUNTIME) @ Target ({ElementType. METHOD, ElementType. TYPE}) public @ interface MyTokyo {String color () default "blue"; // The default value is blueString value () ;}@ MyTokyo (color = "red ", value = "ax") // when no default value is set for the attribute, public class Demo {@ MyTokyo ("xc") must be written for all attributes. // because the default value is set for the color, therefore, you can only write the value that xc represents. You can leave valuepublic static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); // check whether there is any annotation if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo. color ());}}}

Attribute of array type

@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyTokyo {String color() default "blue";String value();int[] arr() default {3,4,5}; }

Note that if there is only one element in the array, arr = 1. You can leave no braces.

@ MyTokyo (color = "red", value = "ax", arr = {1, 2, 4}) public class Demo {@ MyTokyo ("xc ") public static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo. color (); System. out. println (myTokyo. value (); System. out. println (myTokyo. arr (). length );}}}

Enumeration type attributes

// Define an enumeration class

public class Week {private Week(){}public final static Week SUN = new Week();public final static Week MON = new Week();public Week nextDay(){return this==SUN? MON : null;}public String toString(){return this==MON ? "MON":"SUN";}public enum WeekDay{SUN,MON;}}

Define properties of Enumeration type

@ Retention (RetentionPolicy. RUNTIME) @ Target ({ElementType. METHOD, ElementType. TYPE}) public @ interface MyTokyo {String color () default "blue"; String value (); Week. weekDay () default Week. weekDay. SUN; // defines the attribute int [] arr () default {3, 4, 5} of the enumeration type; MyAnotaion2 anotaionArr () default @ MyAnotaion2 ("x ");} @ MyTokyo (anotaionArr = @ MyAnotaion2 ("wjw"), color = "red", value = "ax", arr = {1, 2, 3, 4 }) public class Demo {@ MyTokyo (value = "xc", Day = Week. weekDay. SUN) public static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo. day (). name ());}}}

Annotation type attributes
Public @ interface MyAnotaion2 {String value () ;}@ Retention (RetentionPolicy. RUNTIME) @ Target ({ElementType. METHOD, ElementType. TYPE}) public @ interface MyTokyo {String color () default "blue"; String value (); int [] arr () default {3, 4, 5}; MyAnotaion2 anotaionArr () default @ MyAnotaion2 ("x"); // return the annotation type attribute of MyAnotaion2 annotation}

Annotation type attribute in Annotation

@ MyTokyo (anotaionArr = @ MyAnotaion2 ("wjw"), color = "red", value = "ax", arr = {1, 2, 3, 4 }) public class Demo {@ MyTokyo ("xc") public static void main (String [] args) {Boolean flag = Demo. class. isAnnotationPresent (MyTokyo. class); if (flag) {MyTokyo myTokyo = (MyTokyo) Demo. class. getAnnotation (MyTokyo. class); // obtain the annotation object System. out. println (myTokyo. color (); System. out. println (myTokyo. value (); System. out. println (myTokyo. arr (). length); System. out. println (myTokyo. anotaionArr (). value ());}}}

The attribute return value of the annotation can also be eight basic types, class, and arrays of all types just now.
By reading the documentation, you can better understand the annotations, which are more and more widely used. Pay attention to this application in the future.


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.