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 Java annotations

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "what is Java annotations". The content of the explanation 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 Java annotations".

Meta annotations provided by Java

Java5.0 defines four standard meta-annotations: @ Target @ Retention @ Documented @ Inherited

1.@Target comments

Function: used to describe the scope of use of annotations (that is, where the annotations described can be used)

@ Target illustrates the scope of objects that Annotation modifies: Annotation can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumerated values), method parameters, and local variables (such as loop variables, catch parameters). The use of target in the declaration of the Annotation type makes the goal of its embellishment clearer.

The values (ElementType) are:

CONSTRUCTOR: used to describe constructors

FIELD: used to describe the domain

LOCAL_VARIABLE: used to describe local variables

METHOD: used to describe methods

PACKAGE: used to describe packages

PARAMETER: used to describe parameters

TYPE: used to describe classes, interfaces (including annotation types), or enum declarations

Use case

@ Target (ElementType.TYPE) public @ interface Table {/ * Datasheet name annotation, default is class name * @ return * / public String tableName () default "className";} @ Target (ElementType.FIELD) public @ interface NoDBColumn {}

Annotated Table can be used for annotated classes, interfaces (including annotation types), or enum declarations, while annotated NoDBColumn can only be used for member variables of annotated classes.

2.@Retention comments

Purpose: indicates at what level the annotation information needs to be saved to describe the life cycle of the annotation (that is, to what extent the described annotation is valid)

@ Retention defines how long the Annotation is retained: some Annotation appears only in the source code and is discarded by the compiler, while others are compiled in the class file; the Annotation compiled in the class file may be ignored by the virtual machine, while others will be read when the class is loaded (note that it does not affect the execution of the class, because Annotation and class are separated in use). Using this meta-Annotation, you can limit the "lifecycle" of Annotation.

The values (RetentionPolicy) are:

SOURCE: valid in the source file (that is, source file retention)

CLASS: valid in class files (that is, class retention)

RUNTIME: valid at runtime (that is, retained at runtime)

The Retention meta-annotation type has a unique value as a member, and its value comes from the enumerated type value of java.lang.annotation.RetentionPolicy.

Use case

@ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) public @ interface Column {public String name () default "fieldName"; public String setFuncName () default "setField"; public String getFuncName () default "getField"; public boolean defaultDBValue () default false;}

The attribute value of the RetentionPolicy of the Column annotation is RUTIME, so that the annotation processor can obtain the attribute value of the annotation through reflection, thus doing some runtime logic processing.

3.@Documented comments

Documented is used to describe other types of annotation that should be used as the public API of annotated program members, so they can be documented by tools such as javadoc. Documented is a tag comment and has no members.

Use case

@ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface Column {public String name () default "fieldName"; public String setFuncName () default "setField"; public String getFuncName () default "getField"; public boolean defaultDBValue () default false;}

4.@Inherited comments

The @ inherited meta-annotation is a tag annotation, and @ Inherited states that a certain annotated type is inherited. If an annotation type with the @ Inherited modifier is used for a class, the annotation will be used for a subclass of that class.

Note: the @ Inherited annotation type is inherited by a subclass of the annotated class. The class does not inherit annotation from the interface it implements, and the method does not inherit annotation from the method it overloads.

When the Retention of the annotation annotated by the @ Inherited annotation type is RetentionPolicy.RUNTIME, the reflected API enhances this inheritance. If we use java.lang.reflect to query an annotation of type @ Inherited annotation, reflection code checking will work: check the class and its parent class until it is found that the specified annotation type is found, or reaches the top level of the class inheritance structure.

Use case

/ * @ author taoxiaoran * * / @ Inheritedpublic @ interface Greeting {public enum FontColor {BULE,RED,GREEN}; String name (); FontColor fontColor () default FontColor.GREEN;} custom comments

When using @ interface custom annotations, the java.lang.annotation.Annotation interface is automatically inherited, and other details are automatically completed by the compiler. When defining annotations, you cannot inherit other annotations or interfaces. @ interface is used to declare an annotation, where each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be the base type, Class, String, enum). You can declare the default value of the parameter through default.

Define the annotation format: public @ interface annotation name {definition body}

Supported data types of annotation parameters:

All basic data types (int,float,boolean,byte,double,char,long,short)

String Typ

Class Typ

Enum Typ

Annotation Typ

Arrays of all the above types

How to set the parameters in the Annotation type:

It can only be decorated with public or default (default) access. For example, String value (); here set the method to the default type of defaul;

Parameter members can only use basic types byte,short,char,int,long,float,double, eight basic Boolean data types and String,Enum,Class,annotations data types, as well as arrays of these types. For example, String value (); here the parameter member is String;

If there is only one parameter member, it is best to set the parameter name to value, followed by parentheses. Example: the following example FruitName annotation has only one parameter member.

Simple custom annotations and examples of using annotations:

Package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * Fruit name Note * @ author taoxiaoran * * / @ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface FruitName {String value () default ";} package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention Import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * fruit color annotations * @ author taoxiaoran * * / @ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface FruitColor {/ * Color enumeration * @ author taoxiaoran * / public enum Color {BULE,RED,GREEN} / * Color attribute * @ return * / Color fruitColor () default Color.GREEN;} package annotation;import annotation.FruitColor.Color;public class Apple {@ FruitName ("Apple") private String appleName; @ FruitColor (fruitColor=Color.RED) private String appleColor; public void setAppleColor (String appleColor) {this.appleColor = appleColor;} public String getAppleColor () {return appleColor } public void setAppleName (String appleName) {this.appleName = appleName;} public String getAppleName () {return appleName;} public void displayName () {System.out.println ("the name of the fruit is: Apple");} default value of the annotation element

The annotation element must have a definite value, either specified in the default value of the definition annotation or when using the annotation, and the value of a non-basic type annotation element cannot be null. Therefore, it is a common practice to use an empty string or 0 as the default value. This constraint makes it difficult for the processor to represent the existence or missing state of an element, because in each annotation declaration, all elements exist and have corresponding values, in order to bypass this constraint, we can only define some special values, such as an empty string or a negative number, to indicate that an element does not exist, which has become an idiom when defining annotations. For example:

Package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * Fruit supplier Notes * @ author taoxiaoran * * / @ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface FruitProvider {/ * * supplier No. * @ return * / public int id () default-1 / * * supplier name * @ return * / public String name () default ""; / * * supplier address * @ return * / public String address () default ";}

Annotations are defined and annotated information is added to related classes and class attributes when needed. if there is no responsive annotation information processing flow, annotations can be said to have no practical value. How to make the annotation really play a role, mainly lies in the annotation processing method, the next step we will learn the annotation information acquisition and processing!

Thank you for your reading, the above is the content of "what is Java comments", after the study of this article, I believe you have a deeper understanding of what is Java annotations, 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

Internet Technology

Wechat

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

12
Report