Java's deepening understanding of annotations

Source: Internet
Author: User
Tags deprecated


First, the application of the entry notes

This is a situation that is often encountered.

Package Tokyo.hot;public class Demo {public static void main (string[] args) {new thread (). Stop ();//Draw a line, obviously obsolete method}}
This is an outdated method, then you need to use annotations, tell the compiler, I know this is outdated, I like to use


@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 method of a class before, but now do not want to use, in order not to use this method to cause trouble, then you can add a @deprecated method, which is

An outdated approach

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

HashSet, you need to make a copy of the Equals method, but equals (), the argument is the object type, but accidentally, write another class, this error is not easy to find, then, you need to use the annotation @override, replication

New Thread (New Runnable () {@Overridepublic int run () {}}). Start ();

Annotations, which are equivalent to a tag, add this tag to the package, class, method, variable, field, and so on, telling the compiler that you follow my tag to take the appropriate action


OK, note the fur, already understand!

Ii. definition of annotations and reflection invocation

We want to use a class, then we have to design and write the class, the annotations are the same, we want to use a certain annotation, then we must first design and write the note.

1. Define the Annotation class:

Public @interface Mytokyo {} is the same way you define an interface


2. Class with annotations applied:
@MyTokyo
Class myclass{} to check if this annotation is available on this class

3. Reflection on the "class to which the annotation is applied"
To examine a class, you must use the reflection

@MyTokyopublic class Demo {public static void main (string[] args) {Boolean flag = Demo.class.isAnnotationPresent (Mytokyo). Class);//Check if there is an annotation if (flag) {Mytokyo Mytokyo = (Mytokyo) Demo.class.getAnnotation (mytokyo.class);// Get this Annotated object System.out.println (Mytokyo);}}}

Will find nothing to print
Add annotations to a custom annotation, annotations, and source annotations

@Retention (retentionpolicy.runtime)
Public @interface Mytokyo {}

The meaning of the @Retention (Retentionpolicy.runtime), which is to tell the compiler to keep the custom annotations at run time, because the custom annotations are probably at compile time,
is cleared, Javac The source file is compiled into class, it is possible to remove the annotations from the source program, but also when the class loader loads the class into memory, the annotations in the class are retained, and the
is also a problem.

Special Note: The object in the class file is not a byte code, only the ClassLoader has a class file for security checks and other series of processing, loaded into the memory of the binary is the bytecode

an annotation life cycle has three stages:
1.java source file  2.class file  3. Byte code in memory

so @retention has three values:

(retentionpolicy.source source file stage)

(Retentionpolicy.class class file stage)

(retentionpolicy.runtime run phase)

and the default value is CLASS stage

@ The default value for override is (Etentionpolicy.source source file stage) The default value for the

@SuppressWarnings is (etentionpolicy.source source file stage)

@ Default value for deprecated (retentionpolicy.runtime run phase)


Continue, add an annotation to the automatic annotation @target

@Retention ( Retentionpolicy.source)
@Target (elementtype.method)
public @interface Mytokyo {}

Function: Tell the compiler, Custom annotations can only be loaded on methods where

can use the
@Retention (retentionpolicy.source)

@Target ({Elementtype.method) in both classes and methods. Elementtype.type})

public @interface Mytokyo {}


Note that it is type, not just class, interface can be, so it is more appropriate to use type rather than class


Iii. Adding attributes to annotations


Annotations are powerful because their properties

Annotations are very much like interfaces, and annotation properties are similar to methods

@Retention (Retentionpolicy.runtime) @Target ({elementtype.method,elementtype.type}) public @interface Mytokyo { string color ();//annotation has a property color, return string}

Then the main function is to set the property value

@MyTokyo (color= "Red") public class Demo {public static void main (string[] args) {Boolean flag = Demo.class.isAnnotationPre Sent (mytokyo.class);//Check if there is an annotation if (flag) {Mytokyo Mytokyo = (Mytokyo) Demo.class.getAnnotation (mytokyo.class);// Get this Annotated object System.out.println (Mytokyo.color ());}}}

Print red, which is to add a property to the note, and when it is used, set the property value for it

@Retention (Retentionpolicy.runtime) @Target ({elementtype.method,elementtype.type}) public @interface Mytokyo { String color () default "Blue";//Is bluestring value ();} @MyTokyo (color= "Red", value= "ax")//property is not set by default, all properties must be written to public class Demo {@MyTokyo ("XC")//Because color sets the default value, So it is possible to write only XC represents the value of the property values, can not write valuepublic static void main (string[] args) {Boolean flag = Demo.class.isAnnotationPresent ( Mytokyo.class);//Check if there is an annotation if (flag) {Mytokyo Mytokyo = (Mytokyo) Demo.class.getAnnotation (mytokyo.class);// Get this Annotated object System.out.println (Mytokyo.color ());}}}

Properties of the 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 the elements of the array if there is only one, arr=1, can not write curly braces

@MyTokyo (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);//Get This Annotated object System.out.println (Mytokyo.color ()); System.out.println (Mytokyo.value ()); System.out.println (Mytokyo.arr (). length);}}}

Properties of enum types

Defining an enumeration class

public class Week {private Week () {}public final static Week SUN = new Week ();p ublic final static Week MON = new Week ();p UB Lic Week NextDay () {return This==sun? Mon:null;} Public String toString () {return This==mon? "MON": "SUN";} public enum Weekday{sun,mon;}}

Defining the properties of an enumeration type

@Retention (Retentionpolicy.runtime) @Target ({elementtype.method,elementtype.type}) public @interface Mytokyo { String color () default "blue"; String value (); Week.weekday Day () default week.weekday.sun;//defines the property of the enumeration type int[] Arr () default {3,4,5}; MyAnotaion2 Anotaionarr () Default @MyAnotaion2 ("X");} @MyTokyo ([email protected] ("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);//Get This annotated object System.out.println ( Mytokyo.day (). name ());}}}

Properties for annotation Types
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");//Returns the annotation Type property of a MyAnotaion2 annotation}

Annotation type properties in annotations

@MyTokyo ([email protected] ("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);//Get This Annotated object System.out.println (Mytokyo.color ()); System.out.println (Mytokyo.value ()); System.out.println (Mytokyo.arr (). length); System.out.println (Mytokyo.anotaionarr (). value ());}}}

The property return value of the annotation can also be 8 primitive types, class, arrays of all types just now
By looking at the document you can better understand the annotations, the application of annotations has been more and more extensive, in the future to pay attention to this aspect of the application


Java's deepening understanding of annotations

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.