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 annotations and annotation parsers

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

Share

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

This article mainly explains "how to understand Java annotations and annotation parsers". The content of the explanation is simple and clear, and it is easy to learn and understand. please follow the editor's ideas to study and learn "how to understand Java annotations and annotation parsers".

What is metadata (metadata)

Metadata is translated by metadata, and the so-called metadata is "data about data". More commonly speaking, it is the data that describes the data and the descriptive information of the data and information resources. For example, a text file has data such as creation time, creator, file size, etc., which can be understood as metadata.

In java, metadata is stored in java code in the form of tags, and its existence does not affect the compilation and execution of program code. It is usually used to generate other files or runtime to know the description of the running code. The javadoc and annotations in java belong to metadata.

What is an Annotation?

Annotations have been added since java 5.0 and can be used for annotation packages, classes, methods, variables, etc. For example, our common @ Override, or @ hide,@systemApi,@privateApi in the Android source code, etc.

For @ Override, most people often know what it is but don't know why. Today I'm going to talk about the secret behind Annotation and start the text.

Meta-annotations are the annotations that define annotations, and are the basic annotations that java provides to us to define annotations. In the java.lang.annotation package, we can see the following meta-annotations:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

@ Retention

@ Target

@ Inherited

@ Documented

@ interface

Below we will collect @ Override annotations to explain the use of the five basic annotations.

@ interface

@ interface is the keyword used to declare annotation classes in java. Use this annotation to indicate that the java.lang.annotation.Annotation class will be automatically inherited, which is left to the compiler to complete.

So we want to define an annotation simply by doing the following, using the @ Override annotation as an example

Public @ interface Override {} Note: when defining annotations, you cannot inherit other annotations or interfaces @ Retention

Retention: this annotation is used to define the annotation retention policy, that is, when the defined annotation class exists (source phase, or compilation, or runtime). The note accepts the following parameters: RetentionPolicy.SOURCE,RetentionPolicy.CLASS,RetentionPolicy.RUNTIME, its specific use and meaning are as follows:

Take a look at the retention policy of the @ Override annotation:

@ Retention (RetentionPolicy.SOURCE) public @ interface Override {}

This indicates that the @ Override annotation exists only in the source phase, and javac removes it during compilation.

@ Target

This annotation is used to define the purpose of the annotation, that is, where the annotation can be used, such as methods or fields, and accepts the following parameters:

Take @ Override as an example, it is not difficult to see its goal as the method:

@ Target (ElementType.METHOD) public @ interface Override {}

Up to now, an annotation can be fully defined through @ interface,@Retention,@Target. Let's see the complete definition of @ Override:

@ Target (ElementType.METHOD) @ Retention (RetentionPolicy.SOURCE) public @ interface Override {} @ Inherited

By default, our custom annotations on the parent class will not be inherited by the child class. If you want subclasses to inherit parent annotations, that is, annotations also take effect in subclasses, you need to set @ Inherited when customizing annotations. In general, this annotation is rarely used.

@ Documented

This annotation is used to describe that other types of annotation should be documented by javadoc and appear in api doc.

For example, @ Target using this annotation will appear in the api description.

@ Documented @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.ANNOTATION_TYPE) public @ interface Target {ElementType [] value ();}

With the help of @ Interface,@Target,@Retention,@Inherited,@Documented these five meta-annotations

We can customize the annotations, the first three of which are necessary for any annotation.

Custom annotation

Format:

Public @ interface Annotation name {definition body}

A definition body is a collection of methods, and each method actually declares a configuration parameter. The name of the method is the name of the configuration parameter, and the return value type of the method is the type of the configuration parameter. Unlike the normal method, you can declare the default value of the configuration parameter through the default keyword.

It should be noted that:

Only two permission modifiers, public or default defalt, can be used here

The types of configuration parameters can only use basic types (byte,boolean,char,short,int,long,float,double) and String,Enum,Class,annotation

For comments with only one configuration parameter, it is recommended that the parameter name be set to value, that is, the method name is value.

Once the configuration parameter is set, its parameter value must have a definite value, either specify it when using the annotation, or use default to set the default value for it when defining the annotation, for non-primitive parameter values, it cannot be null.

Like @ Override, annotations without member definitions are called tag annotations.

Annotation processor

We have learned how to define annotations above. For annotations to play a practical role, we need to write corresponding annotation processors for annotations. According to the characteristics of annotations, annotation processors can be divided into run-time annotation processors and compile-time annotation processors. The runtime processor needs to be implemented by reflection mechanism, while the compile-time processor needs to be implemented by APT.

Whether it is a runtime annotation processor or a compile-time annotation processor, the main task is to read annotations and process specific annotations. From this point of view, the annotation processor is very easy to understand.

The Annotation Processor processor is a tool for javac that scans and compiles and processes annotations (Annotation) at compile time. You can define your own annotations and annotation handlers to do something. An annotation processor that takes Java code or (compiled bytecode) as input to generate files (usually java files). These generated java files cannot be modified and will be compiled by javac like their manually written java code. See here to add before understanding, should understand the general process, that is, the marked annotated classes, variables, etc. as input, after the annotation processor processing, to generate the java code you want to generate.

Runtime annotation processor (not recommended)

Students who are familiar with the java reflection mechanism must be very familiar with the java.lang.reflect package. All api in this package support the ability to read runtime Annotation, that is, annotations with the attribute @ Retention (RetentionPolicy.RUNTIME).

The AnnotatedElement interface in java.lang.reflect is the (Class,Method) parent interface of all program elements. We can obtain the AnnotatedElement object of a class through reflection, and then access the Annotation information through the methods provided by the object. The common methods are as follows:

The writing of the runtime annotation processor is essentially to obtain the annotation information through reflection and then do other operations. Compiling a runtime annotation processor is as simple as that. Runtime annotations are often used in parameter configuration class modules.

Compile-time annotation processor

Unlike runtime annotation processors, compile-time annotation processors (Annotation Processor Tool) are written.

APT is used to scan and process annotation information at compile time. A specific annotation processor can take java source files or compiled class files as input, and then output other files, either .java files or .class files, but usually we output .java files. (note: it is not a modification to the source file.) If the output is .java files, these .java file rounds are compiled by javac along with other source files.

You may be wondering at what stage the annotation processor is involved. Well, it's actually before javac starts compiling, which is why we usually want to output .java files.

Annotations were first introduced in java 5, mainly including the related mirror api in the apt and com.sum.mirror packages, when apt and javac are independent. Since java 6, annotation processors have been formally standardized, and apt tools have been integrated directly into javac.

Let's get back to the topic of how to write a compile-time annotation processor. Compiling a compile-time annotation process consists of two steps:

1. Inherit AbstractProcessor and implement your own annotation processor

2. Register the processor and package it into a jar package

Let's first take a look at the format of a standard annotation processor:

Public class MyAnnotationProcessor extends AbstractProcessor {

@ Override

Public Set getSupportedAnnotationTypes () {

Return super.getSupportedAnnotationTypes ()

}

@ Override

Public SourceVersion getSupportedSourceVersion () {

Return super.getSupportedSourceVersion ()

}

@ Override

Public synchronized void init (ProcessingEnvironment processingEnv) {

Super.init (processingEnv)

}

@ Override

Public boolean process (Set

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