Java annotations--using the detailed

Source: Internet
Author: User
Tags deprecated

In some powerful third-party frameworks, we can often see annotations. Xutils, retrofit and so on.

So what are the charms and benefits of annotations that we use when designing frameworks?

understanding of Annotations:
(for personal understanding only)
1, we use annotations to give a token to a constant, method, or class. Then these constants have some kind of feature or some kind of marker.
2, these tags do not participate in our logical processing. This is why it is written outside of the method or class.
3, but we can indirectly influence the logic of the program by getting the markup on the method.
4, annotations are passive, and it affects the program depending on whether the programmer is going to use it.

Thus, the role of annotations is to give a method or class A tag, which is passive and does not affect the logic of the program, but the programmer can use annotations to actively affect the program.

Annotations (Annotation) are a feature of class, Interface (interface), enum (enum) peers after Java5.

As can be seen intuitively, four of them can be directly created.

So, how do annotations behave in Java?

Annotations in the Java system with annotations (meta-annotations)

@Retention @Target @Documented @Inherited four kinds.

1, @Documented
If you add this annotation to your constants, methods, classes (which are so tired each time, simplified to normal), this method is included in the Javadoc document under your project.

This has been seen a lot, many of the three-party tool library interface documentation. Similar to this:

is to add the interface document generated by the note when you need to generate Javadoc.

2, @Inherited
When the inherited is executed, the related code of the parent class is executed automatically, and then the child class is executed.
Look at the code more intuitively:
DBTable was marked @inherited.

@Inherited  public @interface DBTable {       publicnamedefault "";      }
public @interface DBTable2 {      publicnamedefault "";      }  
@DBTable class Super{      Private intSuperprivatem () {return 0; } Public intSuperpublicem () {return 0; }} @DBTable2 class Sub extends Super{      Private intSubprivatem () {return 0; } Public intSubpublicem () {return 0; }  }

The super class is labeled with @inherited annotations. Therefore, when a sub inherits Super, the Subpublicem () method in the sub is executed before the Subpublicem () in super.

3, @Target

Target can define where the annotations are used.

The enumeration value type for which you want to specify a java.lang.annotation.ElementType when used is his "property".

The types of ElementType enumerations are as follows:
Annotation_type: Suitable for ANNOTATION
CONSTRUCTOR: Suitable for construction methods
Field: Applies To field
Local_variable: Suitable for local variables
Method: Applies To methods
Package: For the package
PARAMETER: Suitable for PARAMETER on method
TYPE: For Class,interface,enum

@Target(ElementType.METHOD)public @interface TargetTest {    //这样,这个枚举就只能使用于方法而不能使用与变量或者类了    default"hello";}

4, @Retention

The retention is used to describe the life cycle of the annotation class.

Using retention, you must provide an enumeration that is of type java.lang.annotation.RetentionPolicy.

The Retentionpolicy enumeration has the following 3 types:
SOURCE: Completes the task when the program finishes processing annotation information
Class: The compiler stores annotation in a class file and cannot be read into by the virtual machine
RUNTIME: The compiler stores the annotation in the class file, which can be read by the virtual machine
With these three kinds of retention prolicy you can decide whether annotations are read from source files, class files, or reflected at run time

Note:
If retention annotations are not added on the annotations, the system is added by default and is of type class.
That is, if you want to read this enumerator in the virtual machine, it must be set to runtime.

@Retention(RetentionPolicy.RUNTIME)//定义一个注解,使用Retention标注为RUNTIME该注解被标示为runtime类型,表示该注解最后可以保存在class文件中,并为java虚拟机在运行时读取到public @interface RetentionTest {    default"hello";    String world();    @Retention(RetentionPolicy.CLASS)    //定义一个注解,Retention标注为CLASS,在代码中是获取不到注解中的内容的    @interface RetentionTest1 {        default"hello"//设置默认值为hello    }}

Well, the system comes with, and the annotated annotations (meta-annotations) are the four.
Next look at the system comes with annotations, here is no longer a meta-annotation.

System comes with annotations, non-meta annotations

1, @SuppressWarnings

How the system handles code warnings.

@SuppressWarnings ("Unchecked")
Tells the compiler to ignore unchecked warning messages

@SuppressWarnings ("Serial")
If the compiler appears with this warning message: The serializable class Wmailcalendar does not declare a static final serialversionuid field of type long uses this A note to remove the warning message.

@SuppressWarnings ("deprecation")
If you use the @deprecated comment method, the compiler appears with a warning message. Use this comment to remove the warning message.

@SuppressWarnings ("Unchecked", "deprecation")
Tells the compiler to ignore both unchecked and deprecation warning messages.

@SuppressWarnings (value={"Unchecked", "deprecation"})
Equivalent to @suppresswarnings ("Unchecked", "deprecation")

@SuppressWarnings("unchecked")    privatevoidaaa() {    }

2, @Override

This doesn't have to be explained. Even if you don't use annotations, you'll see more.
Forget it or explain it. Subclasses to override (override) The corresponding method of the parent class.

@Override    privatevoidbbb() {        //super的方法决定你需不需要先执行父类的方法        super.bbb();    }

3, @Deprecated

/**     * Deprecated 注解表示方法是不建议被使用的,过期的     */    @Deprecated    privatevoidccc() {    }

Well, the system enumeration I've already introduced. Next, we'll talk about how to customize enumerations and how to use enumerations.

Custom annotations

Use @interface to declare an annotation (actually automatically inherits the Java.lang.annotation.Annotation interface)

Meta annotations can be used in overlapping

/** * Created by Luhao on 2016/5/20. * Custom annotations * Use @interface to declare an annotation (actually automatically inherits the Java.lang.annotation.Annotation interface) */ @ Documented   @Inherited   @Target  ( Elementtype.method)  @Retention  (retentionpolicy.runtime) public  @interface  Span class= "Hljs-title" >annotationtest  { String name () default   "test" ;    //set the String Type property Value1 for the annotation and set the default value using the Defalut keyword  Enumtest type ();    //set the enumeration type value2  String[] Skills (); //set the array type Value3 }  
publicenum EnumTest {    IT,    EAJUEJI,    CHUSHI,    ZUOJIA,    JINGCHA,    ;}

Add other meta-annotations

/** * Retention: * Use Retention must provide an enumeration for the Java.lang.annotation.RetentionPolicy type * Retentionpolicy enumeration has the following 3 types: * SOURCE: The compiler completes the task when it finishes processing annotation information * Class: The compiler stores annotation in the class file and cannot be read into the RUNTIME by the virtual machine: The compiler stores the annotation in the class file, which can be read by the virtual machine * with these three retention prolicy you can decide that annotations are read from the source file, the class file, or reflected at run time */@Retention(Retentionpolicy.runtime)//Define an annotation, use the retention callout as runtime the note is marked as the runtime type, indicating that the note can finally be saved in the class file and read to the Java Virtual machine at run time Public@ interface retentiontest {String Hello ()default "Hello"; String World ();@Retention(Retentionpolicy.class)//Define an annotation, retention labeled class, in the code is not getting the contents of the annotation    @interfaceRetentionTest1 {String Hello ()default "Hello";//Set the default value to Hello}}
/** * Target: * 使用java.lang.annotation.Target可以定义注解被使用的位置 * 同样,在使用时要指定一个java.lang.annotation.ElementType的枚举值类型为他的“属性” * ElementType枚举的类型如下: * ANNOTATION_TYPE: 适用于annotation * CONSTRUCTOR : 适用于构造方法 * FIELD : 适用于field * LOCAL_VARIABLE : 适用于局部变量 * METHOD : 适用于方法 * PACKAGE : 适用于package * PARAMETER: 适用于method上的parameter * TYPE : 适用于class,interface,enum */@Target(ElementType.METHOD)public @interface TargetTest {    //这样,这个枚举就只能使用于方法而不能使用与变量或者类了    default"hello";}
Usage of annotations
/** * Test class for various enumerations * / Public  class Test {    /** * The Java Annotation system comes with the main following annotations * Only use @interface to define annotations for annotations annotated with annotations.     including @Retention  @Target  @Document  @Inherited four kinds. * * @Document will write this note to Javadoc * @Inherited executes to the inherited line, automatically executes the parent class's related code, executes and then returns to execute the subclass */    Private void Test() {AAA ();        BBB ();    CCC (); }/** * suppresswarnings annotations indicate suppression warnings, program warnings are ignored * /    @SuppressWarnings("Unchecked")Private void AAA() {    }/** * Override annotation denotes the corresponding method of the subclass to override (override) the parent class */    //@Override    Private void BBB() {//super method determines whether you need to perform the parent class first        //super.bbb ();}/** * Deprecated annotation method is not recommended to be used, expired */    @Deprecated    Private void CCC() {    }Private  class testthread extends Thread {        @Override         Public void Run() {        }    }Private  class AAA implements Runnable{        @Override         Public void Run() {} Executorservice Fixedthreadpool = Executors.newfixedthreadpool (5); }PrivateThreadpoolexecutor Threadpoolexecutor;/** * Custom annotations * Need to complete all the attributes in the annotation, if the property has set a default value can be ignored * /    @AnnotationTest(name ="The Girl from Alishan", type = enumtest.it, skills = {"Java","C","C + +"})Private void DDD() {    }/** * Custom annotations can also be used on methods, variables, and classes */    @AnnotationTest(name ="The Girl from Alishan", type = enumtest.it, skills = {"Java","C","C + +"}) String Alishan;@TargetTest(Hello ="The mushroom in Alishan is cool")//callout does not error on method    Private void Eee() {    }//@TargetTest (hello = "alishan mushroom cool")//here will be an error, because he marked on the classString Alishans;/** * The following important methods are available in the interface: * getannotations (Class annotationtype) gets a specified annotation type * getannotations () get all Ann Otation * Getdeclaredannotations () get all declared Annotation * isannotationpresent (class<? extends annotation> Ann Otationclass) Whether this annotation appears * /    @SuppressWarnings("Unchecked")//java The annotated retention policy is source, which means that the warning in this method is ignored    @Deprecated//java Self-Explanatory note retention's policy is runtime    @RetentionTest(Hello ="Dean", World ="very")//Custom annotations retention policy is runtime    @RetentionTest. RetentionTest1 (hello ="AAAAAAA")//Custom annotations retention's policy is class     Public void TestMethod() {System.out.println ("This is a method"); }}
Parameters in annotations that are tagged by a method by reflection
 Public  class maintest {     Public voidMaintest () {Test Testa =NewTest ();//Get the TestMethod method by reflectionclass<test> CLA = Test.class;Try{///Find the TestMethod method in the test classmethod = Cla.getmethod ("TestMethod");method Isannotationpresent () in the//annotatedelement interface to determine whether an incoming annotation type exists            if(Method.isannotationpresent (retentiontest.class) {Method.invoke (testa,Newobject[]{});method Getannotation () in the//annotatedelement interface to get annotations of the incoming annotation typeRetentiontest retentiontest = method.getannotation (retentiontest.class);//Get the attributes in the annotationString Hello = Retentiontest.hello ();                String world = Retentiontest.world (); LOG.I ("Test","Name:"+ Hello +"Age:"+ world); }//Because the enumeration of RETENTIONTEST1 is defined as class, it is not run in the virtual machine            if(Method.isannotationpresent (Retentiontest.retentiontest1.class) {Method.invoke (testa);method Getannotation () in the//annotatedelement interface to get annotations of the incoming annotation typeRetentiontest.retentiontest1 retentiontest = method.getannotation (retentiontest.retentiontest1.class);//Get the attributes in the annotationString Hello = Retentiontest.hello (); LOG.I ("Test","NAMEAAAAA:"+ Hello); }method Getannotations () in the//annotatedelement interface to get all annotationsannotation[] annotations = method.getannotations ();//Loop annotation array prints the name of the annotation type             for(Annotation annotation:annotations) {LOG.I ("Test", Annotation.annotationtype (). GetName ()); }        }Catch(Exception e)        {E.printstacktrace (); }    }}

We can get the data in the annotations and then proactively choose whether or not to act on the method logic through the values of these tags.

Well, this is the use of annotations. Next, we'll talk about the Java reflection mechanism.
Annotations and reflective two things that work together better.

Java annotations--using the detailed

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.