This is the 23rd day of my participation in Gwen Challenge
Introduction of annotation
Annotations, like annotations with a specific purpose, have been introduced since JDK1.5 and later. They are “metadata” used as annotations in front of classes, methods, fields, and parameters in Java source code, on the same level as classes, interfaces, and enumerations.
Annotations can be divided into three categories according to their functions:
- Documentation: Generate corresponding documentation (that is, Java Doc – like documentation) from annotations identified in the code;
- Code analysis: Analysis of code by annotations identified in the code (using reflection);
- Compile the inspection: Allows the compiler to perform basic compilation checks through annotations identified in the code (
@Override
);
Commonly used predefined annotations
@Override
For example, the toString() method we use most is a method of the Object class, and all our written classes are inherited from the Object class, so all our custom classes have toString() methods. However, if the method in our custom class does not exist in the parent class, we cannot use this annotation, or it will fail to compile.
package com.cunyu;
/**
* Created with IntelliJ IDEA.
*
* @author : cunyu
* @version : 1.0
* @email : [email protected]
* @website : https://cunyu1943.github.io
* @date : 2021/6/20 10:04
* @project : JavaWeb
* @package : com.cunyu
* @className : OverrideTest
* @description: * /
public class OverrideTest {
private Integer id;
private String name;
public OverrideTest(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString(a) {
final StringBuffer sb = new StringBuffer("OverrideTest{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\' ');
sb.append('} ');
return sb.toString();
}
public static void main(String[] args) {
Integer id = 101;
String name = "Village Rain Yao";
OverrideTest overrideTest = newOverrideTest(id, name); System.out.println(overrideTest); }}Copy the code
@Deprecated
It is usually used before a method to indicate that the method has expired and is not recommended to continue using it (but it is still valid, although a newer version may be available, and the newer version is recommended).
package com.cunyu;
/**
* Created with IntelliJ IDEA.
*
* @author : cunyu
* @version : 1.0
* @email : [email protected]
* @websiteRain: https://cunyu1943.github.io * @ public number: village *@date : 2021/6/20 10:07
* @project : JavaWeb
* @package : com.cunyu
* @className : DeprecateTest
* @description: * /
public class DeprecateTest {
@Deprecated
public static void sayHello(a) {
System.out.println("Hello World!");
}
public static void newSayHello(a) {
System.out.println("Hello,Welcome to Java !");
}
public static void main(String[] args) { sayHello(); newSayHello(); }}Copy the code
@SuppressWarnings
Warning information is ignored. Common values and their meanings are as follows:
value | describe |
---|---|
deprecation |
Warning when a deprecated class or method is used |
unchecked |
Warning when an unchecked conversion was used |
fallthrough |
whenswitch The block goes straight to the next case withoutbreak When the warning |
path |
Warning when there is a non-existent path in the classpath, source file path, and so on |
serial |
When missing on serializable classesserialVersionUID Warning when defining |
finally |
anyfinally A warning when the clause does not complete properly |
rawtypes |
The generic type is not specified |
unused |
A reference is defined, but not used |
all |
Turn off alerts in all of the above cases |
package com.cunyu;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @author : cunyu
* @version : 1.0
* @email : [email protected]
* @websiteRain: https://cunyu1943.github.io * @ public number: village *@date : 2021/6/20 10:07
* @project : JavaWeb
* @package : com.cunyu
* @className : SuppressWarningsTest
* @description: * /
public class SuppressWarningsTest {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String item = "Village Rain Yao";
@SuppressWarnings("rawtypes")
List items = newArrayList(); items.add(item); System.out.println(items); }}Copy the code
Custom annotations
format
We can customize annotations using @interface in the following format:
public @interface AnnotationName{
// Attribute list... }Copy the code
A simple example is as follows, where AnnoDemo represents the name of our custom annotation, and name(), age(), and score() represent the three attributes of our custom annotation, and we assign default values to each attribute using the keyword default.
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
The principle of
Annotations are essentially equivalent to an interface, its default inherited from Java. Lang. The annotation. The annotation.
public interface AnnotationName extends java.lang.annotation.Annotation{}
Copy the code
parameter
An annotation parameter is similar to a method with no parameters. It is usually recommended to use default to set a default value. The basic requirements for the method are as follows:
- The return value type of a method cannot be
void
; - If a method is defined, then the method needs to be assigned as follows:
- If a keyword is used when defining a method
default
By giving a default initial value to a method, annotations can be used without reassigning the method. - If only one method needs to be assigned and the method name is
value
, then at this timevalue
You can omit it and define the value directly; - When an array is assigned, the value is in curly braces
{}
Wrap, if there is only one value in the array, then{}
Can be omitted;
- If a keyword is used when defining a method
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
In the example above, name(), age(), and score() are the parameters for our custom annotations. When we use this annotation, we assign the parameters as follows.
@annodemo (name = "village yuyao ", age = 26, score = 95.0f)
public class Demo{
……
}
Copy the code
Yuan notes
define
Meta annotations are annotations that can be used to modify other annotations.
Common meta-annotations
@Target
Describe the range of objects that an annotation modifies. The values are as follows:
value | instructions |
---|---|
ElementType.TYPE |
Indicates that you can act on a class or interface |
ElementType.FIELD |
Indicates that you can operate on a member variable |
ElementType.METHOD |
Means you can operate on a method |
ElementType.CONSTRUCTOR |
Indicates that the constructor can be applied |
ElementType.PARAMETER |
Represents parameters that can be applied to a method |
@Target(ElementType.TYPE)
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
@Retention
To constrain the lifecycle of an annotation, the values are as follows:
value | instructions |
---|---|
RetentionPolicy.SOURCE |
Indicates that the annotation is valid in the source code file, and the annotation is discarded by the compiler. (The annotation information is only preserved in the source code, and the annotation information is lost after the source code is compiled and is no longer preserved in the bytecode file.) |
RetentionPolicy.CLASS |
Notation is valid in a bytecode file, and annotations are available in the bytecode file but discarded by the JVM |
RetentionPolicy.RUNTIME |
The representation is valid at run time, when the annotation’s information can be read through reflection |
@Target(ElementType.TYPE)
@Retention(RetentionPoicy.RUNTIME)
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
@Documented
Describes whether other types of annotations are extracted into the API document.
@Target(ElementType.TYPE)
@Retention(RetentionPoicy.RUNTIME)
@Documented
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
@Inherited
This is a tag annotation that describes an annotation that can be inherited by a subclass, but the meta-annotation is only applicable to custom annotations that have been configured with the @target (elementType.type) TYPE, and only applies to class inheritance, not interface inheritance.
@Inherited
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
@Repeatable
This annotation is a new meta-annotation from JDK1.8, which means that the same annotation can be repeated in the same place. In the absence of this annotation, we generally cannot use the same annotation on the same type, but with the introduction of this annotation, we can use the same annotation on the same type.
@Target(ElementType.TYPE)
@Repeatable(AnnoDemos.class)
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
public @interface AnnoDemos{
AnnoDemo[] value();
}
Copy the code
After configuring custom annotations with @REPEATable, we can add more than one of our custom annotations to a type declaration.
@annodemo (name = "village yuyao ", age = 26, score = 88.0f)
@annodemo (name = "xiaoyu ", age = 27, score = 90.0f)
public class Student{
……
}
Copy the code
conclusion
To summarize the above knowledge, we can summarize the process of custom annotations into the following three steps.
- Define an annotation
public @interface AnnoDemo{
}
Copy the code
- Add parameters and set default values
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
- Use meta-annotations to configure our custom annotations
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnoDemo{
String name(a) default"Village Rain Yao";
int age(a) default 20;
float score(a) default60.0 f;
}
Copy the code
In practice, when using meta annotations to configure custom annotations, the @target and @Retention meta annotations must be set, and the @retention value is usually set to retentionPolicy.runtime.
Ok, the above is our annotations related concepts and custom annotations need to master some knowledge points, if you think it helps you, then to a wave of like attention!
This article was first published on the public account: “Village Yuyao”, welcome to search attention!