Basic concepts of annotation

annotation ( metadata ) It provides a formal way for us to add information to our code , We can use this data very conveniently at some time . Make it more popular , Is the description or function added to this method . for example :@Overvide This annotation is used to illustrate that this method can override the parent class .

JDK Notes provided

Java Three annotations are currently built in @Override,@Deprecated,@SuppressWarnnings

* @Override: Used to identify methods , Identifies the method that belongs to the overriding parent class @Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE) public @interface Override { }
* @Deprecated: Used to identify a method or class , Identifies that the class or method is obsolete , Not recommended @Documented
@Retention(RetentionPolicy.RUNTIME) @Target(value={CONSTRUCTOR, FIELD,
{ }
* @SuppressWarnnings: Used to selectively turn off compiler pair classes , method , Member variable , Warning on variable initialization
@Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings {
String[] value(); }
Meta annotation

Java Four meta annotations are provided , That is, the notes that modify the notes . Look at the source code above to find three , Namely :@Target,@Retention,@Document,@Inherited. The main functions are as follows :

How to customize annotation

use @interface Definition notes , Will automatically inherit java.lang.annotation.A
nnotation Interface , Similar to class automatic inheritance Object equally . Each method in the annotation represents a configuration parameter , The return type is the parameter type , It can be done through default Identification parameter default value . The definition is as follows :
import java.lang.annotation.ElementType; import java.lang.annotation.Target;
@Target(ElementType.METHOD) public @interface Test { String value() default "";
Parameter types in annotations

The parameters in the annotation only support the following types :

* All basic types :byte,short,char,int,long,float,double
* String type
* Class type
* enum type
* Annotation type
* Arrays of the above types
If you define other types of parameters, the compiler will report an error .

Notes on using annotations

* If the annotation has only one parameter , It's better to name it value, In this way, the attribute value can be specified directly when using . for example :@Test("hello")
* Use only public And default permission modifiers to modify parameters
* Parameter default value : The annotation parameter must have a definite value . Or give the default value when defining ; Either specify the parameter value when using the annotation .
annotation processor

If there is no way to read the annotation , Then the annotation doesn't make any sense . In the process of using annotations , Annotation processor is essential ,Java Leader reflex mechanism , Complete the annotation processing .

Annotation processor class library

Java Get classes through reflection mechanism , method , Comment on property , therefore java.lang.reflect provide AnnotationElement Support notes , The main methods are as follows :

* boolean is AnnotationPresent(Class<?extends Annotation>
annotationClass): Determine whether the element is annotationClass Annotation modification

* <T extends Annotation> T getAnnotation(Class<T> annotationClass): obtain
On this element annotationClass Type annotation , If not returned null

* Annotation[] getAnnotations(): Returns all annotations on the element

* <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass
): Returns all annotations of the specified type on this element

* Annotation[] getDeclaredAnnotations(): Returns all annotations that directly decorate the element

* <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T>
annotationClass): Returns all annotations that directly decorate the element
Here is an example of the annotation :

Definition notes :
import java.lang.annotation.ElementType; import
java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME) public @interface Test { int max() default
0; int min() default 0; String description() default ""; }
Annotation usage :
public class AnnoationTest { @Test(min = 6,max = 10,description =
" User name length in 6-10 Between characters ") private String name; @Test(min = 6,max =10,description =
" Password length in 6-10 Between characters ") private String pasdword; public String getName() { return
name; } public void setName(String name) { = name; } public String
getPasdword() { return pasdword; } public void setPasdword(String pasdword) {
this.pasdword = pasdword; } }
Annotation processor and test main method :
import java.lang.reflect.Field; public class TestUtil { public static void
valid(Object obj) throws IllegalAccessException { Class<?> clazz =
obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field
field:fields){ Test test = field.getAnnotation(Test.class);// Gets the @Test annotation
if(test != null){ field.setAccessible(true);// Set properties accessible if("class
java.lang.String".equals(field.getGenericType().toString())){// Only the string type is used to judge the length
String value = (String)field.get(obj); if(value != null && ((value.length() >
test.max()) || value.length() < test.min())){
System.out.println(test.description()); } } } } } public static void
main(String[] args){ AnnoationTest annotation = new AnnoationTest();
annotation.setName("abcefg"); annotation.setPasdword("1234567890"); try {
valid(annotation); } catch (IllegalAccessException e) { e.printStackTrace(); }
} }
Whether the property value meets the requirements is checked according to the attribute length set by the user

©2019-2020 Toolsou All rights reserved,
VUE+Canvas Achieve desktop Pinball brick elimination games C/C++ Memory model 2019PHP Interview questions ( Continuously updated )PHPspringboot2 Separation of front and rear platforms ,token Put in header Pit for verification Vue SpringBoot conduct Excel download element-ui Step on pit record 45 The 12-year-old programmer was turned down , Is the workplace wrong ?Python Web frame Pandas Fundamentals of statistical analysis _ data processing (DataFrame Common operations )Java Misunderstanding —— Method overloading is a manifestation of polymorphism ?