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 understand Java Annotation programming

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "how to understand Java annotation programming", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to understand Java annotation programming"!

What is the comment?

Implementation format

From the perspective of the code, we know that the implementation format of the annotation is:

Public @ interface MyAnnotation {attribute list;}

So we have the first intuition that annotations may be an interface. According to the query (through decompilation software), @ interface is actually an inheritance of the custom interface to the annotation interface, and @ interface is actually a syntactic sugar.

Import java.lang.annotation.Annotation; public interface MyAnnotation extends Annotation {attribute list;}

Use location

Class, method, member variable, parameter location.

classification

From different angles, we can have different categories of annotations, but when we know the implementation principle of annotations, we will understand that, in fact, usage and implementation are the same thing.

Source

1. JDK annotations: annotations that are generally used at compile time, such as @ Override, which we are most familiar with.

two。 Third-party framework annotation

3. Custom annotation

Operating mechanism (retention policy)

@ Retention ({retention Policy}) public @ interface MyAnnotation {attribute list;}

1. Source code (SOURCE) comments: comments only exist in the source code, compiled into a .class file does not exist, that is to say, can only play a "look" role.

two。 CLASS annotations: annotations exist in both source code and .class files (JDK comes with annotations that belong to compile-time annotations) and are generally used for syntax checking.

3. RUNTIME annotations: they also work in the runtime and even affect the runtime logic (@ Autowired belongs to runtime annotations). Third-party frameworks and custom annotations generally adopt the retention strategy of runtime, which can achieve dependency injection, aspect programming and other functions.

Meta annotation

In fact, we have seen a meta-annotation (@ Retention) above. Meta-annotations are annotations that are added to annotations to describe annotations. There are five of them.

1. @ Documented

The @ Documented annotation is displayed when the javadoc is generated.

2. @ Target (key)

Limit the location of action, Method, Class and so on.

9. @ Inherited

The @ Inherited annotation modifies a parent class, and if its subclass is not modified by other annotations, its subclass also inherits the parent annotation.

10. @ Retention (key)

The above retention strategy notes affect the role of annotations.

6. @ Repeatable (not important)

The @ Repeatable annotation is used to declare meta annotations of other types of annotations to indicate that the annotations of this declaration are repeatable. The value of @ Repeatable is another annotation, which can contain this repeatable annotation through the value of this other annotation.

How to use

Let's first look at the superficial use of annotations. The simplest.

Using custom annotations is divided into three steps: defining annotations, using annotations, and reading annotations.

Extracted from: https://www.zhihu.com/question/47449512/answer/658228092

As long as we firmly grasp these three steps, we can master the use of annotations.

Definition annotation

Because the basic function of annotations is to determine how the annotated block of code should be executed based on the values in the annotation. Therefore, when defining annotations, we should not only add meta annotations according to the function, but also write the appropriate method name according to the business meaning.

For example, if we were to write a lock annotation:

@ Documented @ Retention (RUNTIME) @ Target ({TYPE, METHOD}) public @ interface Lock {/ / enter the lock name String lockName (); / / lock value String key (); / / lock level int level (); / / exception String exception () default "";}

In an annotation, the types that can be returned are: basic data types, String, enum, Class, other annotations, and one-dimensional arrays of the first few.

Note: if there is no default, then you must enter the parameter when using it.

Use annotations

Note in the place of the note, the parameters that must be entered into the parameter.

Tips: if there is only one function in the note, although you can enter the parameter directly without adding the function name when you use it, it is recommended to write the full name of the function when entering the parameter to enhance the readability of the code.

Read comments

Let's think about it first. if we implement an annotation reading method ourselves, how should we do it?

At the moment, all I can think of is two:

1. Find comments in string or bytecode files: this judgment is not easy to write, and complex strings cannot be handled.

two。 Get comments on classes, methods, and member variables through reflection.

Discerning people can see that 2 is much more reliable than 1, and it is easy to achieve.

One of the easiest ways to read:

Public static void main (String [] args) throws NoSuchMethodException {Class modelClazz = Module.class; Method method = modelClazz.getMethod ("lock", null); Lock annotationLock = method.getAnnotation (Lock.class); / / get value String lockName = annotationLock.lockName ();}

This is also the basic implementation principle of framework annotations, because you need to scan the package to get the specific code blocks of the annotations.

For facet programming, with the introduction of dependency aspectj, we have a simpler invocation method:

/ / public Object around (ProceedingJoinPoint pjp) throws Throwable {MethodSignature signature = (MethodSignature) pjp.getSignature (); Lock lock = signature.getMethod () .getAnnotation (Lock.class); lock.lockName ();}

For more information about aspect programming and joinpoint, please refer to:

Https://blog.csdn.net/qq_15037231/article/details/80624064

The role of annotations

At this point, we can summarize the role of annotations.

* programming hints

The retention policy is a source code comment, usually a suggestive comment, such as @ deprecated.

* used for section to reduce duplicate code

The retention policy is the running comment, and 0 intrusion changes the running effect of the function, which is generally used for repetitive functions, such as log output, data format checking, etc.

* simplify configuration information and project structure

Mainly for the role of the framework springboot. Because annotations can be taken as values, you can also enter configuration information while setting the default configuration information.

* format check

It is generally used to check the syntax of the code, which is found in the annotation package with jdk, such as @ Override.

At this point, I believe you have a deeper understanding of "how to understand Java annotation programming". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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