Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the notes in Java?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the annotation in Java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the annotation in Java".

Java annotations are a new feature of jdk1.5, and they are widely used. Let's first take a look at the application of annotations. Baidu encyclopedia says:

We can see that the role of annotations is threefold:

Write doc documents: this is the @ return and @ author that we often use. After adding these annotations, you can use jdk to automatically generate the corresponding API documents for us.

Compiler checking: this is also very common @ Override, and it is very powerful, which I will introduce in a future article

Code analysis: this is the focus of this article. This is as powerful as compilation checking, but there are some performance problems compared with compilation checking because it uses reflection.

Background development of the three major frameworks of SSH, as well as our Android side of the retrofit,ButterKnife,Lombok and other frameworks and plug-ins are also a large number of annotations. Here I'm going to demonstrate what annotations are useful and how to use them by hand with a fake ButterKnife.

Let's first look at a piece of code.

Public class MainActivity extends AppCompatActivity {@ OnClick (R.id.test_btn) void test () {test_tv.setText ("Congratulations, successful binding!") ;} @ FindViewByID (R.id.test_tv) TextView test_tv;@Overrideprotected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); ButterKnife.bindView (this);}}

This is a basic activity with two controls, Button and TextView

The text of TextView was changed after I clicked Button. All I do is ButterKnife.bindView (this) and add 2 annotations, which realizes the binding of the control, saves a lot of code that has nothing to do with business, and is a lot more concise.

After looking at the function of the annotation, do you want to know how it is done? then I will take a look at what it is, how to use it, how to use it.

What is a comment?

Officially, it is called metadata, which is a kind of data that describes data. Therefore, it can be said that annotations are the metadata of the source code. Use it to describe and mark our source code.

How to define a comment

Here is a @ OnClick annotation that I defined above

@ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) public @ interface OnClick {int value () default 0;}

It can be seen that just like defining a class, class is changed to @ interface, and some important information about this annotation is illustrated by several original annotations at the top, as follows:

The J2SE5.0 version provides four meta-annotations in java.lang.annotation, specifically for other annotations:

@ Documented-whether the comment will be included in the JavaDoc

@ Retention-when to use this annotation

@ Target?-where are the annotations used

@ Inherited-whether subclasses are allowed to inherit this annotation

@ Documented- is a simple Annotations tag annotation that indicates whether the annotation information is added to the java document or not.

@ Retention- defines the lifecycle of the annotation, which is important and must be specified. Here is an introduction to the three lifecycles.

RetentionPolicy.SOURCE-discarded during compilation. These annotations no longer make any sense after compilation, so they do not write bytecode. @ Override and @ SuppressWarnings all fall into this category.

RetentionPolicy.CLASS-discards when the class is loaded. Useful in bytecode file processing. Annotations use this method by default.

The RetentionPolicy.RUNTIME- is never discarded, and the annotation is retained at run time, so the information of the annotation can be read using the reflection mechanism. Our custom annotations usually use this approach.

Target-indicates where the annotation is used. If it is not explicitly stated, the note can be placed anywhere. Here are some available parameters. It is important to note that attribute annotations are compatible. If you want to add annotations to all seven attributes and exclude only one attribute, then you need to include all attributes in the definition target.

ElementType.TYPE: used to describe classes, interfaces, or enum declarations

ElementType.FIELD: used to describe instance variables

ElementType.METHOD

ElementType.PARAMETER

ElementType.CONSTRUCTOR

ElementType.LOCAL_VARIABLE

Another comment on ElementType.ANNOTATION_TYPE

ElementType.PACKAGE is used to record package information of java files

@ Inherited-defines the relationship between the annotation and the subclass

So how should the content in the annotate be defined?

Annotations only supports basic types, String, and enumerated types. All properties in the comment are defined as methods and allow default values to be provided.

@ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) @ interface Book {public enum Priority {LOW, MEDIUM, HIGH} String author () default "Yash"; int price () default 20 position status status () default Status.NOT_STARTED;}

See how to use it.

@ Todo (priority = Todo.Priority.MEDIUM, author = "zsq", status = Todo.Status.STARTED) public void incompleteMethod1 () {}

The field is assigned a value in the form of field name =, and if no value is assigned, the default value is used. If there is only one attribute in the annotation, you can name it "value" without indicating the attribute name, such as the @ OnClick annotation I defined.

Well, after so much effort to get to know him, it's time to see how to use it.

We define our own annotations and apply them to the methods of business logic. Now we need to write a user program to call our comments. Here we need to use the reflection mechanism. If you are familiar with reflection code, you will know that reflection can provide class names, methods, and instance variable objects. All of these objects have getAnnotation (), which is used to return annotation information. We need to convert this object to our custom annotation (after checking with instanceOf ()), and we can also call the methods in the custom annotation.

All of these objects have getAnnotation ()!

All of these objects have getAnnotation ()!

All of these objects have getAnnotation ()!

The important API is said three times, and the other methods used are also very important. The following code demonstrates that more API references can be used to consult the JDK documentation.

Specific to the example of our article, the guy who called the annotation is the ButterKnife we just used in MainActivity. Let's set the listening annotation to see what it has done.

Public static final void bindView (final Activity activity) {traversalMethod (activity); traversalField (activity);}

In the ButterKnife.bindView (this) we called, we took the instance of MainActivity and iterated through all the methods in it through reflection:

Private static void traversalMethod (final Activity activity) {Method [] methodArray = getObjectMethodArray (activity); for (final Method method:methodArray) {if (isAnnotationPresent (method)) {int viewID = getViewID (method); setOnClickListenerForControl (activity, method, viewID);}} private static Method [] getObjectMethodArray (Activity activity) {return activity.getClass (). GetMethods ();}

Then determine whether the method is annotated by us:

Private static boolean isAnnotationPresent (Method method) {return method.isAnnotationPresent (OnClick.class);}

If we use the annotation method, we obtain the space ID saved in the annotation through the annotation, and set click monitoring for it through the example of MainActivity, and call the annotated annotation method in the monitoring.

Private static int getViewID (Method method) {return method.getAnnotation (OnClick.class). Value ();} private static void setOnClickListenerForControl (final Activity activity, final Method method, int viewID) {activity.findViewById (viewID) .setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {try {method.invoke (activity);} catch (IllegalAccessException e) {e.printStackTrace ();} catch (InvocationTargetException e) {e.printStackTrace ();});}

The great task has been completed! Isn't it simple?

Thank you for your reading, the above is the content of "what is the annotation in Java". After the study of this article, I believe you have a deeper understanding of what the annotation in Java is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report