Java Advanced Features-annotations, this is perhaps the most simple and understandable article

Source: Internet
Author: User

Java annotations are jdk1.5 after the new features, for its application is very broad, we first look at the application of annotations, Baidu Encyclopedia said:

As we can see, the role of annotations has three aspects:

Write Doc documents: This is a very common @return and @author, add these annotations, we can use the JDK to help us automatically generate the corresponding API documentation

Compile check: This is also very common @Override, and the function is very powerful, I will be in a future article to introduce

Code Analysis: This is the focus of this article. This is as much a powerful feature as a compile check, but there are some performance problems with the compilation check because it uses reflection.

In the background development of SSH three framework, and we Android Retrofit,butterknife,lombok and other frameworks and plugins are also a lot of use of annotations. Here I will be a fake butterknife by hand to illustrate the use of annotations, how to use.

Let's first look at the snippet code

publicclassmainactivityextendsappcompatactivity{@OnClick (R.ID.TEST_BTN) voidtest () {Test_tv.settext ("Congratulations, the bindings are successful!) ");} @FindViewByID (R.ID.TEST_TV) TextView test_tv; @OverrideprotectedvoidonCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Butterknife.bindview (this);}}

This is one of the most basic activity, with 2 controls, button and TextView

The TextView text is changed after I click the button. And what I did was just Butterknife.bindview (this) and add 2 annotations, so that the control is bound, eliminating a lot of business-independent code, is not much more concise.

Read the function of the annotation is not very want to understand how it is done, next I will see what it is, how to use, how to use

What are annotations

Officials call it metadata, a data that describes the data. So, it can be said that the annotation is the source code metadata. It can be used to describe and tag our source code.

How to define an annotation

Here's a @OnClick note that I've defined above

@Target (Elementtype.method) @Retention (retentionpolicy.runtime) [email protected] {intvalue () default0;}

As you can see and define a class, just change the class to @interface, and at the top there are several original annotations that illustrate some important information about this annotation, as follows:

The j2se5.0 version provides four types of meta-annotations in java.lang.annotation, specifically annotated with other annotations:

@Documented – whether the annotations will be included in the Javadoc

@Retention – When to use this annotation

@Target? – Where the annotations are used

@Inherited – whether subclasses are allowed to inherit the annotation

@Documented – a simple annotations tag annotation that indicates whether to add annotation information to a Java document, usually without a tube.

@Retention – Defining the life cycle of this annotation is important and must be specified, the following is an introduction to 3 life cycles

retentionpolicy.source– is discarded during the compile phase. These annotations are not completed after compilation

Makes no sense, so they do not write bytecode. @Override, @SuppressWarnings belong

to such annotations.

The retentionpolicy.class– is discarded when the class is loaded. Useful in the processing of bytecode files.

Annotations are used this way by default.

retentionpolicy.runtime– is never discarded, and the runtime retains the annotation, so you can make

The information of the annotation is read with the reflection mechanism. Our custom annotations are typically used this way.

@Target – Indicates where the note is used. If not explicitly stated, the annotations can be placed anywhere. The following are some of the available parameters. Note that the attribute annotations are compatible, and if you want to add annotations to all 7 attributes, just exclude an attribute, then you need to define the target to include all the attributes.

Elementtype.type: Used to describe a class, interface, or enum declaration Elementtype.field: Used to describe instance variables ElementType.METHODElementType.PARAMETERElementType.CONSTRUCTORElementType.LOCAL_ Variableelementtype.annotation_type Another comment Elementtype.package the package information used to record Java files

@Inherited – Define the relationship of this comment and subclass

So what is the definition of the content in the annotation body?

Annotations only supports basic types, string, and enumeration types. All attributes in the note are defined as methods and allow default values to be provided.

@Target (Elementtype.method) @Retention (retentionpolicy.runtime) @interfaceBook {publicenumpriority {low, MEDIUM, High}stringauthor () Default "Yash"; Intprice () default20; Statusstatus () defaultstatus.not_started;}

See how it's used.

@Todo (priority = Todo.Priority.MEDIUM, author = "Zsq", status = Todo.Status.STARTED) PublicvoidincompleteMethod1 () {}

Assigns a value to a field in the form of field name =, and if not assigned, the default value is used. If there is only one attribute in the annotation, you can name it directly as "value", without having to label the property name, such as the @OnClick annotation I defined.

Well, it takes a lot of energy to get to know him, and it's time to see how we can use it.

We define our own annotations and apply them to the methods of business logic. Now we need to write a user program that calls our annotations. Here we need to use the reflection mechanism. If you are familiar with reflection code, you know that reflection can provide class names, methods, and instance variable objects. All of these objects have getannotation () This method is used to return the annotation information. We need to convert this object to our custom annotations (after using the instanceof () check), and we can invoke the method inside the custom comment.

All of these objects have getannotation ()!

All of these objects have getannotation ()!

All of these objects have getannotation ()!

Important API say 3 times, another use of several methods is also very important, the following code will demonstrate, more API use reference can go to consult the JDK document.

Specifically to our example of this article, call the annotated guy is the butterknife we just used in the mainactivity, we set the listening annotations to see what it did

Publicstaticfinalvoidbindview (finalactivity activity) {Traversalmethod (activity); Traversalfield (activity);}

In the Butterknife.bindview we call (this) we get an instance of mainactivity and iterate through all the methods inside it:

Privatestaticvoidtraversalmethod (finalactivity activity) {method[] Methodarray = Getobjectmethodarray (activity); for (Finalmethod Method:methodarray) {if (isannotationpresent) {Intviewid = Getviewid (method); Setonclicklistenerforcontrol (activity, method, ViewID); }}}privatestaticmethod[] Getobjectmethodarray (activity activity) {Returnactivity.getclass (). GetMethods ();

Then judge whether the method is annotated by us:

Privatestaticbooleanisannotationpresent (method) {returnmethod.isannotationpresent (onclick.class);}

If we annotate with annotations, we get the space ID saved in the annotations through annotations, and we use the Mainactivity instance to set the click Listener for it, and invoke the method of annotation annotation within the listener.

Privatestaticintgetviewid (method) {returnmethod.getannotation (Onclick.class). Value ();} Privatestaticvoidsetonclicklistenerforcontrol (finalactivity Activity,finalmethod Method,intviewID) { Activity.findviewbyid (ViewID). Setonclicklistener (Newview.onclicklistener () {@OverridepublicvoidonClick (view view ) {try{Method.invoke (activity);} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (InvocationTargetException e) {e.printstacktrace ();}} });}

Done! Isn't it simple?

We realize the function of Butterknife by using reflection to get annotations, but the article begins with the lack of reflection performance. In fact, Butterknife itself is not a reflection, but the use of apt tools at compile time can get all the methods, fields, and their annotations, thus avoiding the use of reflection, solve the problem of performance. The next article I will explain the 3rd in this article, that is, butterknife actual use of the method, our own butterknife to butterknife the official implementation method.

Java Advanced Features-annotations, this is perhaps the most simple and understandable 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.