Annotation annotation
This is the back-end small class of the monastery. Each article is shared from
[background introduction] [knowledge analysis] [common problems] [solutions] [coding practice] [extended thinking] [more discussion] [References]
Eight aspects of in-depth analysis of back-end knowledge / skills. This article shares:
[annotation]
title:
[small java class of Xiuzhen academy] annotation
Opening remarks:
Hello, I'm the third student of Xi'an Branch of it Academy. I'm an honest, pure and kind java programmer. Today, I'd like to share with you the annotation annotation, the knowledge point in deep thinking, Java task 7 on the official website of the Academy
(1) Background:
1.1 annotation concept
Annotation is a new feature introduced in Java 5. Its Chinese name is annotation. It provides a secure annotation like mechanism, Used to associate any information or metadata with program elements (classes, methods, member variables, etc.) (class, method, member variable) plus more intuitive and clear description, which is independent of the business logic of the program and used by the specified tool or framework. Annotation, like a modifier, is applied to the declaration statements of package, type, construction method, method, member variable, parameter and local variable.
PS: Java annotation is some meta information attached to the code, which is used for parsing and using some tools during compilation and runtime, and plays the function of description and configuration. Annotations do not and cannot affect the actual logic of the code, but only play an auxiliary role. Included in Java Lang.annotation package.
1.2 use of notes
1. Generate documents. This is the most common and the earliest annotation provided by Java. Commonly used are @ param, etc
2. Track code dependencies and implement alternative configuration file functions.
3. Format check at compile time. If @ override is placed in front of the method, if your method does not override the superclass method, it can be checked during compilation.
(2) Knowledge analysis:
2.1 annotation of common standards:
1.)Override
java. Lang. override is a tag type annotation that is used as a annotation method. It shows that the marked method overrides the method of the parent class and plays the role of assertion. If we use this annotation, the java compiler will warn us of a compilation error when a method does not override the parent method.
2.)Deprecated
Deprecated is also a tag type annotation. When a type or type member uses the @ deprecated modifier, the compiler will not encourage the use of the annotated program element. Therefore, using this modification has a certain "continuity": if we use this obsolete type or member in the code by inheritance or override, although the inherited or overridden type or member is not declared @ deprecated, the compiler still needs to alarm.
3.)SuppressWarnings
Suppresswarning is not a tag type annotation. It has a member of type string [] whose value is the prohibited warning name. For the javac compiler, the warning names valid by the - xlint option are also valid for @ suppresswarnings, and the compiler ignores unrecognized warning names.
2.2 yuan notes
java. Lang.annotation provides four meta annotations, specifically for other annotations (meta annotations need to be used when customizing annotations):
@Documented – will annotations be included in Javadoc
@Retention – when to use this annotation
@Target – where are annotations used
@Inherited – whether subclasses are allowed to inherit the annotation
1.) @ retention – defines the lifecycle of the annotation
● RetentionPolicy. Source: discarded at compile time. These annotations no longer have any meaning after compilation, so they do not write bytecode@ Override and @ suppresswarnings belong to this type of annotation.
● RetentionPolicy. Class: discarded when the class is loaded. It is useful in the processing of bytecode files. Annotations use this method by default
● RetentionPolicy. Runtime: the annotation will never be discarded, and the annotation will be retained during the runtime. Therefore, the information of the annotation can be read using the reflection mechanism. Our custom annotations usually use this method.
2.) target – indicates where the annotation is used. The default value is any element, indicating where the annotation is used. Available ElementType parameters include
● ElementType. Constructor: used to describe the constructor
● ElementType. Field: member variables, objects, attributes (including enum instances)
● ElementType. LOCAL_ Variable: used to describe local variables
● ElementType. Method: used to describe the method
● ElementType. Package: used to describe a package
● ElementType. Parameter: used to describe parameters
● ElementType. Type: used to describe class, interface (including annotation type) or enum declaration
3.) @ documented – a simple annotations tag annotation indicating whether annotation information is added to the Java document.
4.) @ inherited – defines the relationship between the annotation and the subclass
@Inherited meta annotation is a tag annotation, @ inherited describes that a marked type is inherited. If an annotation type decorated with @ inherited is used for a class, the annotation will be used for the subclass of the class.
(3) Frequently asked questions:
Custom annotation
(4) Solution:
Some rules for writing custom annotation classes:
1. Annotation type is defined as @ interface, and all annotations will automatically inherit Java Lang. annotation is an interface, and you can't inherit other classes or interfaces
2. Parameter members can only be modified with public or default access rights
3. Parameter members can only use eight basic data types: byte, short, char, int, long, float, double and Boolean, and data types such as string, enum, class and annotations, as well as arrays of these types
4. To get the annotation information of class methods and fields, you must obtain the annotation object through java reflection technology, because you have no other method to obtain the annotation object
(5) Coding practice:
1. Custom annotation
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Qiao {
String value() default "";
2. Simple use
@Qiao("qiao")
public class People {
@Qiao ("Joe")
public void test1(){}
public void test2(){};
}
3. The main content is to obtain the information carried by the annotation through reflection and make logical judgment
Class clazz = Class. forName("annotation.People");
//Gets all annotations on the class
Annotation[] annotations = clazz. getAnnotations();
for (Annotation a : annotations) {
System. out. println("annotations========" + a);
}
//Get Qiao annotation
Qiao annotation = (Qiao) clazz. getAnnotation(Qiao.class);
System. out. println("annotation======" + annotation);
//Output value
System. out. println("value========" + annotation.value());
//Judge Qiao Is class on this class
System. out. println(clazz.isAnnotationPresent(Qiao.class));
4. On the basis of the above, do a simple processing
public static void process(String clazz) throws ClassNotFoundException {
int passed = 0;
int Failed = 0;
//Get class instance
Class c = Class. forName(clazz);
//Acquisition method
Method[] method = c.getmethods();
for (Method m : method) {
System. out. println(m);
//System. out. println(m.isAnnotationPresent(Testable.class));
//Judge whether there is testable annotation on the method
if (m.isAnnotationPresent(Qiao.class)) {
System. out. println(m);
//If passed + 1 exists
passed++;
} else {
//If failed + 1 does not exist
Failed++;
}
}
System. out. println("passed========" + passed);
System. out. println("Failed========" + Failed);
}
public static void main(String[] args) throws ClassNotFoundException {
Test2. process("annotation.People");
}
(6) Expand thinking:
6.1 @RequestMapping
//Never mind, the alias of the URL
String name() default "";
//The following path and value represent the same meaning@ Aliasfor annotations make different attributes work the same
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
//Request method
RequestMethod[] method() default {};
//Specifies the type of parameter
String[] params() default {};
//Header pass parameter
String[] headers() default {};
//Specifies the format of the data transfer parameter
String[] consumes() default {};
//Specifies the type of content returned
String[] produces() default {};
How does the dispatcher servlet quickly find the corresponding interface method through the URL?
Simplify understanding, (1) @ requestmapping (2) is added to the controller's method. Similarly, through the above simple demo demonstration, first obtain all methods through reflection, and judge whether there is @ requestmapping annotation on each method through the method; if there is, obtain the data in value = "/ U / people" and use this path (or spliced as a full path) is the key value; the method name is value and stored in a map; (3) the above processes are completed during initial loading. When there is a request for access, query the corresponding method in the map by splicing or intercepting the amount path as the key and run it directly.
(7) References:
Baidu Encyclopedia
(8) More discussion:
Q1: role of annotation
A1: annotations only serve as flags (such as serializable) and carry data. They have nothing to do with code logic. Specific logic processing needs to be written by programmers.
Q2:java. Lang package should have five basic annotations
A2: in addition to the above three, there are: @ safevarargs heap pollution warning, @ functionalinterface specifies that the interface is a functional interface;
Q3: meta annotation @ inherited
A3: allow subclasses to inherit the annotation;
When the annotation @ Z (including meta annotation @ inherited) on a class a verifies whether there is also @ Z annotation on the subclass of class A, it will return true;
(9) Thanks:
(10) Conclusion:
That's all for today's sharing. You are welcome to like, forward, leave messages and make bricks~
Ppt link video link