What are annotations?
Annotation, also called metadata. A code-level description. It is a feature introduced in JDK1.5 and later versions, and is at the same level as classes, interfaces, and enumerations. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, etc., and is used to explain and annotate these elements.
We can understand annotations as special marks in the code. These marks can be read during compilation, class loading, and runtime, and corresponding processing can be performed. Through annotations, developers can embed supplementary information in the source code without changing the original code and logic.
1. The role of annotations
Write documentation: Generate documents through the annotations identified in the code [Generate document doc documents]
Code analysis: Pass Analyze the code using annotations identified in the code [Use Reflection]
Compilation Check: The compiler can implement basic compilation checks through the annotations identified in the code [@Override]
2. The predefined annotation
@Override
in the JDK detects whether the method marked by this annotation is inherited from the parent class (interface).
@Deprecated
The content identified by this annotation indicates that it is outdated. When used, there will be a horizontal line.
SuppressWarnings
Suppress warnings, generally pass the parameter all @SuppressWarnings("all").
(Video tutorial recommendation: java video)
3. Custom annotation
Format
public @interface 注解名称 { 属性列表; }
Essence: Annotation is essentially an interface, which inherits the Annotation interface by default. You can decompile the class file through the javap class name.class command
public interface MyAnno extends java.lang.annotation.Annotation { }
Attributes:
in the annotation Properties are abstract methods in interfaces.
Requirements:
The return value type of the attribute can only be the following types
Basic data type
String
Enumeration
Annotation
Arrays of the above types
public @interface MyAnno { int age(); String name(); //枚举类型 Person per(); //注解类型 MyAnno2 anno2(); //数组类型 String[] strs(); } //枚举类Person public enum Person { P1,P2; }
Note:
defines the attributes, and you must assign values to the attributes when using them. Use commas to separate multiple attributes. On, so the method name in general annotations is generally taken as the attribute name;
If you use the default keyword to give the attribute a default initialization value when defining an attribute, you do not need to assign a value to the attribute when using it;
If there is only one attribute that needs to be assigned a value, and the name of the attribute is value, the value can be omitted and the attribute value is defined directly;
When assigning an array, the value is wrapped in {}. If there is only one value in the array, {} can be omitted.
@MyAnno(age=20, name="zhangsan", per=Person.P1, anno2=@MyAnno2, strs={"zhangsan","lisi"}) public class Test { }
Meta-annotation: annotation used to describe annotations
@Target
The position where the currently described annotation can act. This annotation has only one attribute that is value and returns the value Is an array of ElementType enumeration type.
Common values of ElementType:
TYPE: Can be applied to classes
METHOD: Can be applied to methods
FIELD: Can be applied to member variables The above
@Rentention
describes the stage when the annotation is retained. The annotation has only one attribute value, and the return value is the value of the RetentionPolicy enumeration type
RetentionPolicy
SOURCE: The currently described annotations will not be retained in the class file
CLASS: The currently described annotations will be retained in the class bytecode file, but will not be read by the JVM
RUNTIME: The currently described annotation will be retained in the class bytecode file and read by the JVM. Custom values generally take this value
@Documented
Whether the currently described annotation is extracted into the api document
@Inherited
Whether the currently described description annotation is inherited by the subclass
Generally used are the first two meta-annotations.
4. Use of annotations
Use annotations in the program: Get the attribute values defined in these
// pro 注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface pro { String className(); String methodName(); } //在程序中使用注解 @pro(className="anli.Demo1", methodName = "show1") public class UseAnno { public static void main(String[] args) throws Exception { //获取这个类的class对象 Class<UseAnno> useAnnoClass = UseAnno.class; //获取指定的注解类子类对象 pro proAnno = useAnnoClass.getAnnotation(pro.class); //执行注解中的方法,获取注解中属性的值 String className = proAnno.className(); String methodName = proAnno.methodName(); }
Through getAnnotation in the Class class () method, what is obtained is the object of the implementation class of the annotation class. With the object, you can execute the method in the annotation, and the return value is the attribute value set when using the annotation. In fact, a subclass implementation object of the annotation interface is generated in the memory
public class ProImpl implements Pro{ public String className(){ return "cn.itcast.annotation.Demo1"; } public String methodName(){ return "show"; } }
Recommended tutorial: Getting started with java development
The above is the detailed content of How to better use java annotations. For more information, please follow other related articles on the PHP Chinese website!