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

How to write Java annotations

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

Share

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

This article introduces the relevant knowledge of "how to write Java comments". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The original note is not mysterious.

An annotation is a tag or a special comment in vernacular, and it is nothing if there is no operation to parse these tags.

The format of annotations, like similar or methods, has its own special syntax, which is described in more detail below.

So how to parse the annotations? This is going to use the powerful reflection capabilities of Java. Reflection should be used by all of you. You can get all kinds of information about this class, such as member variables, methods, etc., through the class object. Can the annotation tags be obtained through reflection? Of course you can.

So the principle of annotations is actually very simple, in essence, it is to dynamically obtain annotation tags through the reflection function, and then perform different operations according to different annotations, such as @ Autowired can inject an object to assign values to variables.

Is it very restless to see here? come on, make a note yourself.

To build a rocket, write a note yourself.

For everyone to understand, here first introduce a scene: online education is popular, the manager asked me to write a module to achieve student information management function, considering the distributed concurrency problem, the manager asked me to add distributed locks.

The manager asked me how many days I could handle it. I said at least three days. If the brain complements the following code:

Before using annotations

After the manager left, I was thinking, can I just take one day to finish it and spend the remaining two days writing blog strokes? Suddenly inspired, I can extract the repeated code logic and implement it with annotations to save the code. Haha, write quickly.

The whole method is much more refreshing after using annotations, and my little sister HR praised me for my good writing.

After using annotations

The code has been written on the library, and now I am writing a blog. Is it very simple, elegant and powerful? how to do it? it is mainly divided into three steps: 1 open the refrigerator door, 2 put the elephant in, 3 close the refrigerator door. All right, we're going too far. Let's move on.

The first step is to define the three main components of an annotation

An annotation can be simply broken down into three parts:

Part one: note disintegration

The definition of annotations is a bit similar to that of interface, except that the previous one adds an @ symbol, which must not be saved.

Part II: annotation variables

The syntax of the annotation variable is somewhat similar to the method defined in the interface, with the variable name followed by a pair of parentheses, except that the annotation variable can be followed by a default value. In addition, the return value can only be a Java base type, a String type, or an enumerated class, not an object type.

Part III: meta-annotations

To put it bluntly, meta-annotations (meta-annotation) are annotations for annotations. Are you a little dizzy? this kind of annotations are built-in in advance by JDK and can be used directly. It doesn't matter if I don't know much. Anyway, there are only four of them. Let's memorize them: @ Target @ Retention @ Documented @ Inherited.

Target comments

Used to describe the scope of use of annotations, that is, where modified annotations can be used.

Annotations can be used to modify packages, types (classes, interfaces, enumerations, annotation classes), class members (methods, constructors, member variables, enumerated values), method parameters and local variables (such as loop variables, catch parameters). When defining the annotation class, using @ Target can more clearly know which objects it can be used to modify. The specific value range is defined in the ElementType.java enumeration class.

For example, the annotations for Redis locks we wrote above can only be used on methods.

Retention comments

It is used to describe the time range of annotation retention, that is, the life cycle of annotations. Three cycles are defined in the RetentionPolicy enumeration class:

Public enum RetentionPolicy {

SOURCE, / / Source files are reserved

CLASS, / / keep at compile time, default value

RUNTIME / / Runtime retention, which can be used to obtain annotation information through reflection

}

The @ Override annotation, as we know it, can only be retained in the source file, and the annotation disappears after the code is compiled. For example, the annotations for Redis locks we wrote above are retained at run time, where information can be obtained through reflection.

Documented comments

It is simple to describe whether to retain the annotated information when using the javadoc tool to generate help documentation for a class.

Inherited comments

Annotations modified by Inherited annotations are inherited, and if the parent class uses annotations modified by @ Inherited, its subclasses automatically inherit the annotation.

OK, we have defined the annotation at this step, but how does this annotation work? Keep looking.

The second step is to implement the business logic of the annotations

In the first step, we found that the defined annotation (@ EnableRedisLock) has no business logic, only some variables. Don't forget that our annotation is to enable the function of Redis distributed locks, so how on earth does this annotation achieve the function of locking and releasing locks? This requires us to make use of the powerful function of reflection.

Operation of annotations

With the help of the aspect function, the EnableRedisLock annotation is used as a pointcut, and the code logic here is automatically executed as long as the annotation is marked on the method.

After you get the annotated object through the reflection mechanism, you can execute the common logic of locking and unlocking. Redis implementation of distributed locks I believe we are already familiar with, here is no longer verbose.

The third step is to use the annotation @ EnableRedisLock (lockKey = "student", expireTime = 10, timeUnit = TimeUnit.SECONDS, retryTimes = 5) in the business code.

Public void method1 (Student student) {

/ / write business logic here

} "how to write Java comments" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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