Get the App
SLTechnology News&Howtos  ›  Development  › 

How to design and use your own annotations in Java

Shulou Source: shulou.com Published: 2022-06-02 21:05:14 09月12日 Update

Today, I will talk to you about how to design and use your own notes in Java. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

We have used the @ Override @ Deprecated @ SuppressWarning annotations provided to us by JDK, which are provided to us by JDK, and we are just using what others have written, so can we write our own annotations? Of course you can.

The notes we wrote include three links:

1. The declaration of the annotation, that is, the definition of the annotation class.

A declaration of annotations in the form of @ interface.

Package me.test; import java.lang.annotation.*; / / Import all comments @ Retention (RetentionPolicy.RUNTIME) / / explain as follows @ Target (ElementType.TYPE) / / explain as follows public @ interface MyAnnotation {} @ Retention (RetentionPolicy.RUNTIME)

The annotation retention period is specified, the annotation life cycle is three, and the three values of the RetentionPolicy enumeration represent three declaration cycles, and the default is CLASS.

Enumerate constant summary CLASS

The compiler records comments in the class file, but VM does not need to retain comments at run time.

RUNTIME

The compiler will record the comments in the class file, and VM will retain the comments at run time, so it can be read reflectively.

SOURCE

Comments to be discarded by the compiler.

@ Target (ElementType.TYPE)

This logo comment should be marked there, where several enumerated values of ElementType represent the location where the comment should be written.

CONSTRUCTOR

Constructor declaration FIELD

Field declaration (including enumeration constants) LOCAL_VARIABLE

Local variable declaration METHOD

Method declaration PACKAGE

Package declaration PARAMETER

Parameter declaration TYPE

Class, interface (including annotation type), or enumeration declaration

2. Annotated classes or methods are used.

@ MyAnnotation class A {}

3. Use reflection to manipulate annotations, see the code for details.

The Class class has one method:

A getAnnotation (Class annotationClass)

This method takes an annotated bytecode parameter and then returns the annotation object identified by the class, because identifying an annotation is equivalent to generating an annotation object.

BooleanisAnnotationPresent (Class

Tags: Comments methods comments three identifiers contents cycles compilers compilers settings code representatives parameters objects constants files reflections interpretations runs things Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS MySQL Apple MariaDB