In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces what is the role of Annotation annotations in Java, the content is very detailed, interested friends can refer to, hope to be helpful to you.
one。 What is Annotation?
In the usual development process, we see a lot of @ Override,@SuppressWarnings,@Test style code is annotations, annotations are tags placed in front of classes, constructors, methods, properties, and parameters.
two。 The role of Annotation
Give a class, method, etc. Added a note, this link is only a mark, will not have any impact on the code itself, need the cooperation of the follow-up link, need other methods to give business logic processing to the note. Just like we posted a shared location on Wechat, it is of no use at this time. Only when everyone else enters this shared location can the distance between us be clear and we will know how to get together.
Comments fall into three categories:
2.1 comments used by the compiler
For example, @ Override,@SuppressWarnings are annotations used by the compiler to tell the compiler something, rather than entering the compiled .class file.
Override: tell the compiler to check to see if the method of the parent class is overridden
@ SuppressWarnings: tells the compiler to ignore the warning generated by this code
For developers, they are all used directly, and no other operations are needed.
2.2 comments used in the class file
Some notes that need to be modified to the .class bytecode file through the tool, some tools will dynamically modify the .class file marked with an annotation when the class is loaded, so as to achieve some special functions, after one-time processing is completed, it will not exist in memory, and will be used by very low-level toollibraries and frameworks, which are generally not involved for developers.
2.3 run-time read comments
Annotations that have always existed in JVM and can be read during runtime are also the most commonly used annotations, such as @ Controller,@Service,@Repository,@AutoWired,Mybatis @ Mapper,Junit @ Test of Spring. Many of these annotations are tool framework customizations that play a special role during runtime, and developers can also customize such annotations.
three。 Define Annotation
We use @ interface to define an annotation
/ * define a Table annotation * / public @ interface Table {String value () default ";} / * define an Colum annotation * / public @ interface Colum {String value () default"; String name () default"; String dictType () default";}
This simply defines an annotation.
The annotations we defined above mainly use String types, but in fact they can also be basic data types (not wrapper classes) and enumerated types.
Annotations also have a convention, the most commonly used parameter should be named value, and we usually set a default value through the default parameter.
But is this enough for our use? I want to use the @ Table annotation only on classes and @ Colum annotations only on attributes? And the three types of annotations mentioned at the beginning, most developers use runtime annotations, so we define them, right?
To answer these questions, you need to introduce a concept "meta-annotation".
3.1 yuan annotation
Annotations that can be modified are meta-annotations. Java has defined some meta-annotations, which we can use directly.
3.1.1 @ Target
As the name implies, specify the target object used by the annotation, and the parameter is ElementType []
Public @ interface Target {/ * Returns an array of the kinds of elements an annotation type * can be applied to. * @ return an array of the kinds of elements an annotation type * can be applied to * / ElementType [] value ();}
Here are the properties defined in the ElementType enumeration. When Target is not set, everything else is equivalent to configuration except TYPE_PARAMETER,TYPE_USE.
Public enum ElementType {/ * * can modify classes, interfaces, enumerations * / TYPE through ElementType.TYPE, / * * can modify class attributes * / FIELD through ElementType.FIELD, / * * can modify methods * / METHOD through ElementType.METHOD, / * * can modify parameters (such as constructors or methods) * / PARAMETER through ElementType.PARAMETER / * * you can modify the constructor * / CONSTRUCTOR via ElementType.CONSTRUCTOR, / * * modify the local variable * / LOCAL_VARIABLE inside the method through ElementType.LOCAL_VARIABLE, / * * modify the annotation * / ANNOTATION_TYPE through ElementType.ANNOTATION_TYPE, / * modify the package * / PACKAGE through ElementType.PACKAGE / * can be used before the declaration of Type * * @ since 1.8 * / TYPE_PARAMETER, / * can be used in all places where Type is used (such as generics, type conversions, etc.) * * @ since 1.8 * / TYPE_USE}
Let's mainly talk about ElementType.TYPE_PARAMETER and ElementType.TYPE_USE added by ElementType.PACKAGE and 1.8.
ElementType.PACKAGE
@ Target (ElementType.PACKAGE) public @ interface Table {String value () default "";}
The meaning is used to modify the package, but when we use it to modify the package, it indicates an error.
We follow the prompts to create the package-info.java file. It should be noted here that new-> Java Class through IDE cannot be created, but needs to be created through the new File file.
@ Tablepackage annotation;class PackageInfo {public void hello () {System.out.println ("hello");}}
ElementType.TYPE_PARAMETER and ElementType.TYPE_USE
The two are said together because they have something in common. All are added after Java1.8.
@ Target (ElementType.TYPE_USE) public @ interface NoneEmpty {String value () default "";} @ Target (ElementType.TYPE_PARAMETER) public @ interface NoneBlank {String value () default "";}
It is clear that the annotation @ NoneBlank modified with ElementType.TYPE_PARMETER cannot be compiled when generics are used, and can only be used for generic declarations of classes, while the annotation @ NoneEmpty modified by ElementType.TYPE_USE can.
3.1.2 @ Retention
Can be used to define the lifecycle of annotations. The parameter is enumerated RetentionPolicy, including SOURCE,CLASS,RUNTIME
Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.ANNOTATION_TYPE) public @ interface Retention {/ * * Returns the retention policy. * @ return the retention policy * / RetentionPolicy value ();} public enum RetentionPolicy {/ * exists only in the source code, the compilation phase will be discarded and will not be included in the class bytecode file. * / SOURCE, / * [default policy], which exists in the class bytecode file and is discarded when the class is loaded. * / CLASS cannot be obtained at runtime, and / * will never be discarded. You can use reflection to get the information of this annotation. The most common use of custom annotations. * / RUNTIME} 3.1.3 @ Documented
Indicates whether to add information about this comment to the javadoc document
3.1.4 @ Inherited
Define the relationship between the annotation and the subclass, use the custom annotation declared by this annotation, when used on the class, the subclass will automatically inherit the annotation, otherwise, the subclass will not inherit the annotation. Note that annotations declared with @ Inherited are valid only if they are used on a class and are not valid for methods, properties, and so on.
@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Inheritedpublic @ interface Person {String value () default "man";} @ Personpublic class Parent {} / / subclass also has @ Person annotation class Son extends Parent {} 3.2 definition summary
Define annotations with @ interface
Multiple parameters can be added. Value is used for core parameters as agreed, and default values can be set for each parameter. Parameter types include basic types, String and enumerations.
You can use meta-annotations to modify annotations. Meta-annotations include multiple, and @ Target and @ Retention,@Retention must be set to RUNTIME.
four。 Annotation processing
We have already mentioned that the light configuration annotation actually has no effect, and we need to use the corresponding code to implement the logic that the annotation wants to express.
Annotations are also a kind of class after definition, and all annotations are inherited from java.lang.annotation.Annotation, so you need to use reflection API to read annotations.
/ / the defined annotation @ Target (ElementType.FIELD) @ Retention (RetentionPolicy.RUNTIME) public @ interface Colum {String value () default "; / / is used to indicate the Chinese meaning of String name () default";}
Modify the properties of a class with the annotation @ Colum
Public class Person {@ Colum (name = "name") private String name; @ Colum (name = "gender") private String gender; @ Colum (name = "age") private int age; @ Colum (name = "address") private String address; public String getName () {return name;} public void setName (String name) {this.name = name;} public String getGender () {return gender } public void setGender (String gender) {this.gender = gender;} public int getAge () {return age;} public void setAge (int age) {this.age = age;} public String getAddress () {return address;} public void setAddress (String address) {this.address = address;}}
Read the Chinese meaning of all the fields of this class through reflection, save them to list, and then print them out.
Public static void main (String [] args) throws ClassNotFoundException {List columNames = new ArrayList (); Class clazz = Class.forName ("annotation.Person"); / / get all properties of Person class Field [] fields = clazz.getDeclaredFields (); for (Field field: fields) {/ / get Colum annotation Colum colum = field.getAnnotation (Colum.class) for this attribute / / or you can first determine whether the annotation field.isAnnotationPresent (Colum.class) exists; / / take out the Chinese meaning configured by the annotation and put it into the collection columNames.add (colum.name ());} / print the collection columNames.forEach ((columName)-> System.out.println (columName));}
The results are as follows:
Name, sex, age, address
For example, we have some common application scenarios where we need to export the list on the website into an excel table. We configure the column name by annotating, and then read the value of each field that the entity needs to export (whether it needs to be exported or can also be configured through annotations) through reflection, so as to implement the components exported by excel.
five。 Summary
This article only explains the basic concepts of annotations, the functions of annotations, the functions and usage of several meta-annotations, and explains the treatment of annotations through a simple example, which is not comprehensive. The basic Api of annotations is explained through Field, but annotations can also modify classes, constructors, methods, etc., and there are corresponding annotation processing methods. You can check the relevant contents of the API manual by yourself. More or less the same, there is something wrong, please criticize and correct, hope to make progress together, thank you!
Follow the official Wechat account [programmer's Dream] and focus on full-stack technologies such as Java,SpringBoot,SpringCloud, microservices, Docker and front-end separation.
On what the role of Annotation annotations in Java is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.