What are annotations?
That’s a question that many first-time developers have, right? Annontation is a new feature introduced in Java5, called annotations in Chinese. It provides a secure annotation-like mechanism for associating any information or metadata with program elements (classes, methods, member variables, and so on). Add more intuitive and explicit descriptions of application elements (classes, methods, member variables) that are independent of the application’s business logic and are used by the specified tool or framework.
Annontation is used like a modifier in declarations of packages, types, constructors, methods, member variables, parameters, and local variables. Java annotations are meta-information attached to code that is parsed and used by tools during compilation, runtime, and configuration. Annotations do not and cannot affect the actual logic of the code, but only serve as an aid. Included in the java.lang.annotation package.
The use of annotations:
1. Generate documentation. This is the most common and the earliest annotation provided in Java. 2. Track code dependencies to achieve the function of replacing configuration files. For example, Dagger 2 dependency injection, which will be very useful for future Java development with a lot of annotation configuration; 3. Format checking at compile time. If @Override comes before a method, it will be checked at compile time if your method does not override a superclass method.
The principle of annotations:
Annotations are essentially a special interface that inherits annotations, implemented by dynamic proxy classes generated by the Java runtime. When we get annotations through reflection, we return $Proxy1, the dynamic proxy object generated by the Java runtime. Through a proxy object call custom annotations (interface) method, will eventually call AnnotationInvocationHandler invoke method. This method indexes the corresponding value from the Map memberValues. The source of memberValues is the Java constant pool.
Yuan comments:
Java.lang. Annotation provides four meta-annotations that are used specifically to annotate other annotations (you need to use meta-annotations when customizing annotations) :
-
@documented – Whether an annotation will be included in JavaDoc
-
@Retention — When is this annotation used
-
@target – Where are annotations used
-
@Inherited – Whether subclasses are allowed to inherit this annotation
1.@Retention – Define the life cycle of the annotation
-
Retentionpolicy. SOURCE: discarded at compile time. These annotations are no longer meaningful after compilation, so they are not written to bytecode. @Override and @SuppressWarnings fall into this category.
-
Retentionpolicy. CLASS: Discarded when the CLASS is loaded. Useful in the processing of bytecode files. This is the default for annotations
-
Retentionpolicy.runtime: The annotation is never discarded and is retained at RUNTIME, so it can be read using reflection. Our custom annotations usually use this approach.
2.Target – Indicates where the annotation is used. The default value is any element, indicating where the annotation is used. The ElementType parameters available 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 methods
-
Elementtype. PACKAGE: Used to describe packages
-
Elementtype. PARAMETER: Used to describe parameters
-
Elementtype. TYPE: Used to describe classes, interfaces (including annotation types), or enum declarations
3.@Documented – A simple Annotation, Called Annotations, indicates whether annotation information is added to a Java document.
4.@Inherited – defines the relationship between the annotation and the subclasses
An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class.
Common standard annotations:
1.Override
Java.lang.Override is a tag type annotation that is used as an annotation method. It indicates that the method being tagged overrides the parent class’s method, acting as an assertion. If we use this annotation in a method that does not override a superclass method, the Java compiler will alert us with a compilation error.
2.Deprecated
Deprecated is also a tag type annotation. When a type or a type member uses the @deprecated modifier, the compiler discourages the use of the annotated program element. So there is some “continuity” in the use of this modifier: if we use an obsolete type or member in our code by inheritance or overwriting, the compiler still alerts us, even though the inherited or overwritten type or member is not declared as @deprecated.
3.SuppressWarnings
SuppressWarning is not a tag type annotation. It has a member of type String[] whose value is the forbidden warning name. For the Javac compiler, warning names that are valid with the -xLint option are also valid with @Suppresswarings, and the compiler ignores unrecognized warning names. @SuppressWarnings(“unchecked”)
Custom annotations:
Some rules for writing custom annotation classes:
-
Annotation type is defined as @interface. All annotations automatically inherit java.lang.Annotation and cannot inherit from other classes or interfaces.
-
Parameter members can only be qualified with public or default access rights
-
Parameter members can only use the basic data types byte, short, char, int, long, float, double, and Boolean, and the data types String, Enum, Class, and Annotations, as well as arrays of these types.
-
To get Annotation information for class methods and fields, you must use Java’s reflection technology to get the Annotation object, because you have no other way to get the Annotation object
-
Annotations can also not define members, but then annotations are useless
PS: Custom annotations need to use meta-annotations
Custom annotation examples:
FruitName.java
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @retention (RUNTIME) @documentedPublic @Interface FruitName {String Value () default ""; }
Copy the code
FruitColor.java
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; / / @target (FIELD)@Retention(RUNTIME) @documentedPublic @Interface FruitColor {/** ** color */ public enum Color{ BLUE,RED,GREEN}; /** * fruitColor() default color.green; }
Copy the code
FruitProvider.java
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; / / @target (FIELD)@Retention(RUNTIME) @documentedPublic @Interface FruitProvider {/** ** Documentedpublic */ public int id() default -1; /** * public String name() default ""; Public String address() default ""; }
Copy the code
FruitInfoUtil.java
import java.lang.reflect.Field; Public class FruitInfoUtil {public static void getFruitInfo(class <? > < span style =" max-width: 100%; clear: both; min-height: 1em; String strFruitColor=" color: "; String strFruitProvicer=" Vendor info: "; Field[] fields = clazz.getDeclaredFields(); for(Field field :fields){ if(field.isAnnotationPresent(FruitName.class)){ FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class); strFruitName=strFruitName+fruitName.value(); System.out.println(strFruitName); } else if(field.isAnnotationPresent(FruitColor.class)){ FruitColor fruitColor= (FruitColor) field.getAnnotation(FruitColor.class); strFruitColor=strFruitColor+fruitColor.fruitColor().toString(); System.out.println(strFruitColor); } else if(field.isAnnotationPresent(FruitProvider.class)){ FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class); StrFruitProvicer =" fruitProvider number: "+ fruitprovider.id ()+" fruitProvider name: "+ "fruitProvider address: "+ fruitprovider.address (); System.out.println(strFruitProvicer); }}}}
Copy the code
Apple.java
import test.FruitColor.Color; */public class Apple {@fruitName ("Apple") private String appleName; @FruitColor(fruitColor=Color.RED) private String appleColor; @FruitProvider(id=1,name=" Hongfuji Group ", Address =" HongFuji Tower, 89 Yan 'an Road, Xi 'an city, Shaanxi Province ") private String appleProvider; 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 setAppleProvider(String appleProvider) { this.appleProvider = appleProvider; } public String getAppleProvider() { return appleProvider; } public void displayName(){system.out.println (" fruit name: apple "); }}
Copy the code
FruitRun.java
/ * * * * / output in a public class FruitRun {public static void main (String [] args) {FruitInfoUtil. GetFruitInfo (Apple. Class); }}
Copy the code
The results are as follows:
Name of fruit: Apple Fruit Color: RED Supplier No. : 1 Name of supplier: Shaanxi Hongfuji Group Supplier Address: Hongfuji Building, No. 89 Yan ‘an Road, Xi ‘an city, Shaanxi Province
Further reading
Spring notes the difference between @Resource and @autowired
SpringBoot notes
Working Principles of Web applications
HashMap thinking and handwritten implementation
How to present yourself in less than 1 minute?
Author: Jia Shubing
Source: https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html