Java annotations and its practice and principles in Butternife

Source: Internet
Author: User
Tags deprecated throw exception

1.background

Before going to a company, talking about Java annotations, there are several ways to ask Java annotations, and then I mention the Butternife and afinal annotation tools in Android, We know Butternife in the 6.1 version of the time or Injectview, can be 7.1 when the use of bind, what is the difference between it. Simply put, Injectview is annotated at run time, and bind is executed when Android is installed, which is sure to be more efficient.

Now let's talk about Java annotations.

2.What are annotations

We need to learn a little more about JDK 5.0 's new annotation (Annotation) technology because spring supports @aspectj, and @aspectj itself is a JDK 5.0-based annotation technology. So learning the annotated knowledge of JDK 5.0 helps us to better understand and Master spring's AOP technology.

For Java developers, when writing code, in addition to the source program, we use the Javadoc tag to annotate classes, methods, or member variables so that the Javadoc tool can be used to generate Javadoc documents that match the source code. These javadoc tags, such as @param, @return, and so on, are annotation tags that provide annotated information for third-party tools that describe program code. Friends who have used Xdoclet will be more impressed, like struts, hibernate provide xdoclet tags, and use them to quickly generate the corresponding program code configuration file.

JDK5.0 annotations can be seen as the extension and development of Javadoc tags and xdoclet tags. In JDK5.0, we can customize these tags and get the annotations in the class in the reflection mechanism of the Java language to accomplish certain functions.

Annotations are collateral information for the code, which follows a basic principle: annotations do not directly interfere with the operation of the program code, and the code works correctly regardless of adding or removing annotations. The Java language interpreter ignores these annotations, and the third-party tool is responsible for processing the annotations . Third-party tools can use annotations in the code to indirectly control the operation of program code, which reads the annotated information through the Java reflection mechanism and changes the logic of the target program based on that information, which is the approach that spring AOP takes to provide support for @aspectj.

The syntax of annotations is simple, except for the use of the @ symbol, which is basically consistent with the inherent syntax of Java, with three annotations built into Java, defined in the Java.lang package.

@Override : can only be used on the method, to tell others that this method is to rewrite the parent class.

@Deprecated: It is recommended that others do not use the old API, when compiling will be used to generate a warning message, can be set in the program all the elements.

@SuppressWarnings : indicates that some improper compiler warning messages are turned off.

Attach the java5.0 version of the note

public enum Retentionpolicy {    /**     * Annotation are only available in the source code.     */    source,    /**     * Annotation is available in the source code and in the class file, but not * at     runtime. T The is the default policy.     */    class,    /**     * Annotation is available in the source code, the class file and was     * available at runtime .     */    RUNTIME}
We look at Butternife's annotated View code.

@Retention (Retentionpolicy.class) @Target ({Elementtype.field}) public @interface injectview {    int value ();}

3.Defining Annotations

The following is an instance of defining annotations.

@Target (Elementtype.type)
@Retention (Retentionpolicy.runtime)
@Documented
@Inherited
Public @interface Description {

String value ();
}

Now the IDE has provided us with the new portal, annotated format is public+@interface + name.

All annotation classes are implicitly inherited from Java.lang.annotation.Annotation, and annotations do not allow explicit inheritance to other interfaces.

An annotation can have more than one member, and a member declaration and an interface method declaration are similar, where we define only one member, and the declaration of a member has the following limitations:

A) members are declared in a non-argument-no-throw exception, such as Boolean value (String str), Boolean value (), throws exception, and so on, which are illegal;

b) You can specify a default value for a member by default, such as String level (), default "Low_level", and "int High" () default 2 is legal, and of course you can not specify a default value;

c) member types are restricted, and valid types include primitive types and their enclosing classes, String, class, enums, annotation types, and array types of the above types. such as Forumservice value (), List foo () is illegal.

d) If the annotation has only one member, the member name must be named value (), and the member name and assignment number (=) can be ignored when used, such as @Description(" instance using annotations"). When an annotation class has more than one member, an assignment number is not used if only the value member is assigned, and if multiple members are assigned at the same time, you must use an assignment number, such as @declareparents (value = "Naivewaiter" , Defaultimpl = Smartseller.class).

e) Note Classes can have no members, annotations without members are referred to as identity annotations, and the interpreter processes to identify the presence or absence of annotations;

The annotation definition contains four meta-annotations, @target, @Retention, @Documented, @Inherited, respectively. The functions of the meta-annotations are as follows:

1) @Target

Indicates where the annotation is used, and the possible elemenettype parameters include:

? The Elemenettype.constructor constructor declaration.

? Elemenettype.field domain declarations (including enum instances).

? Elemenettype.local_variable local variable declarations.

? Elemenettype.method method declaration.

? Elemenettype.package Package declaration.

? The Elemenettype.parameter parameter declaration.

? Elemenettype.type class, interface (including annotation type) or enum declaration.

2) @Retention

Indicates at what level the annotation information is saved. The optional retentionpolicy parameters include:

? Retentionpolicy.source annotations are discarded by the compiler.

? Retentionpolicy.class annotations are available in the CLASS file, but are discarded by the VM.

? Retentionpolicy.runtime VMS will also retain annotations at run time, so the information of annotations can be read through the reflection mechanism.

To cite an example, such as @override inside the retention set to source, compiled successfully do not have the information of these checks, on the contrary, @Deprecated inside the retention set as runtime, This means that in addition to being warned at compile time which deprecated method is used, it is possible to find out whether the method is deprecated when executed.

3) @Documented

Include this note in the Javadoc

4) @Inherited

Allow subclasses to inherit annotations from parent class

4.Use

@Description (value= "instance using annotations")
public class Testannotation {

}

Use the syntax of annotations:@< annotation name > (< member name 1>=< member value 1>,< member name 1>=< member value 1>,...)

if the member is an array type, you can{}to be assigned, you should know that you have used butternife. such as:

@AnnoExample (id= 2868724, synopsis = "Enable Time-travel", engineer = "Mr Peabody")

public class Parseannotation {public   static void Main (string[] args) {   class Cls=null;try {cls = Class.forName ("C N.java.description "); Method[] method = Cls.getmethods (); if (Cls.isannotationpresent (Description.class)) {  //returns annotations   of the specified type according to the annotation type Description des = (Description) cls.getannotation (description.class);   SYSTEM.OUT.PRINTLN ("Note description:" + des.value ());}} catch (ClassNotFoundException e) {e.printstacktrace ();}   }

The output results are as follows:

Annotation Description: Using an instance of an annotation

In JDK5.0, reflective objects such as package, Class, Constructor, method, and field have new ways to access annotation information: <t extends Annotation>t getannotation ( Class<t> Annotationclass), which supports direct return of annotation objects via generics.







Java annotations and its practice and principles in Butternife

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.