1. Annotation overview
What is an annotation: Annotation annotation is a code-level description. It is a feature introduced by JDK1.5 and later versions, and it is at the same level as classes, interfaces, and enumerations
Contrast notes:
Comments are for programmers, and comments are for programs. (Annotations will not affect the normal execution of the code)
The role of annotations:
Mainly used to replace XML and properties configuration files
2. Annotations provided by JDK
annotation | illustrate |
---|---|
@Deprecated | Indicates that the modified method is obsolete. Deprecated methods are deprecated, but can still be used |
@Override | JDK5.0 represents the method of overriding the parent class; jdk6.0 can also represent the method of implementing the interface |
@SuppressWarnings | Indicates that warnings are suppressed. If there are compilation warnings in the modified class or method, it will be ignored by the compiler. |
3. Parameters of @SuppressWarnings
parameter | illustrate |
---|---|
deprecation | or obsolete |
rawtypes | Ignore type safety |
unused | ignore do not use |
unchecked | Ignore security checks |
null | ignore null pointers |
all | ignore all |
4, define annotations, use the @interface keyword
public @interface Zfwy { }
4.1, define annotations with attributes
public @interface Zfwy { String name() default "My son is not my fish"; }
Attribute format: modifier return value type attribute name () [default default value]
- Modifier: The default value is public abstract , and can only be public abstract.
- Return value types: primitive types, strings String, Class, annotations, enumerations, and one-dimensional arrays of the above types
- property name: custom
- default Default value: can be omitted
4.2, the complete example
public @interface MyAnno { int age() default 1; String password(); Class myqin(); // kind Zfwy zfwy(); // annotation Color color(); // enumerate String[] aggs(); // array } enum Color { RED, BLUE; }
5. The use of annotations
Use the format: @ annotation class name ( attribute name = value , attribute name = value , …)
@MyAnno(age = 22,password = "zfwy",myqin = Myqxin.class,zfwy = @Zfwy,color = Color.BLUE,aggs = {"itcast","itcatstow"}) @Override public void say(){ System.out.println("Coldly said that this method has been rewritten"); }
Notes on using annotations:
Annotations can have no attributes, if there are attributes, they need to be enclosed in parentheses. For example: @Zfwy or @Zfwy()
Attribute format: attribute name = attribute value, multiple attributes are separated by commas. For example: @Zfwy(name="sub non-my fish")
If the attribute name is value and there is currently only one attribute, value can be omitted.
If the attribute type is an array and there are multiple values, you need to add {}. For example: arrs = {"itcast","ithermy"}
If the property type is an array and there is only one value, {} can be omitted. For example: arrs = "itcast"
On a content, annotations can only be used once and cannot be used repeatedly.
6, custom annotation: parsing
If you add annotations to classes, methods, etc., you generally need to obtain the data set on the annotations, then we must parse the annotations.
The JDK provides the java.lang.reflect.AnnotatedElement interface to allow annotations to be obtained through reflection at runtime.
method | illustrate |
---|---|
boolean isAnnotationPresent(Class annotationClass) | Determine whether the current object has annotations |
T getAnnotation(Class annotationClass) | Get the specified annotation on the current object |
Annotation[] getAnnotations() | Get the current object and all annotations inherited from the parent class |
Annotation[] getDeclaredAnnotations() | Get all annotations on the current object |
7. Test
User.java
@MyAnno(age = 22,password = "zfwy",myqin = Myqxin.class,zfwy = @Zfwy,color = Color.BLUE,aggs = {"itcast","itcatstow"}) public class User { }
use
public class Demo01 { public static void main(String[] args) { // Check if there is a MyAonn annotation on the User class boolean b = User.class.isAnnotationPresent(MyAnno.class); // result is false System.out.println(b); } }
When running the above program, we expect the output to be true, but it is false.
Although there is @MyAnno1 annotation on the class, it cannot be obtained after running.
Because each custom annotation needs to be modified by defining a meta-annotation, it can be really parsed and used.
8. Define meta-annotations
Meta-annotations: Annotations used to decorate annotations. (The JDK-provided annotations used to decorate custom annotations)
JDK provides 4 meta-annotations:
@Retention is used to determine the life cycle of the decorated custom annotation
RetentionPolicy.SOURCE: Modified annotations can only exist in the source code, not bytecode class es.
RetentionPolicy.CLASS : Modified annotations can only exist in source code and bytecode, not in runtime memory.
RetentionPolicy.RUNTIME : The modified annotation exists in source code, bytecode, memory (runtime).
@Target is used to determine where the decorated custom annotation is used
ElementType.TYPE decoration class, interface
ElementType.CONSTRUCTOR decorated construct
ElementType.METHOD modified method
ElementType.FIELD decorated field
@Documented Whether to include this annotation when using javaDoc to generate api documentation (understand)
@Inherited Whether the subclass inherits if the superclass uses the modified annotation. (learn)
annotation | illustrate |
---|---|
Retention | Indicates how long to keep annotations of the annotation type |
Target | Indicates the kind of program element used by the annotation type |
Documented | Indicates that a certain type of comment will be documented through javadoc and similar default tools |
Inherited | Indicates that the annotation type is automatically inherited |
enumerate | illustrate |
RetentionPolicy | Annotation retention policy |
ElementType | Program element type |
9. Modify the MyAnno annotation class
@Retention(RetentionPolicy.RUNTIME) // Runtime test instance public @interface MyAnno { int age() default 1; String password(); Class myqin(); // kind Zfwy zfwy(); // annotation Color color(); // enumerate String[] aggs(); // array } enum Color { RED, BLUE; }
reuse
public class Demo01 { public static void main(String[] args) { // Check if there is a MyAonn annotation on the User class boolean b = User.class.isAnnotationPresent(MyAnno.class); // result is true System.out.println(b); } }
10. Test case: mock @Test annotation
10.1, annotation class @MyTest
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyTest { }
10.2, target class AnnotationDemo.java
public class AnnotationDemo { @MyTest public void run1(){ System.out.println("run1 method is executed. . ."); } @MyTest public void run2(){ System.out.println("run2 method is executed. . ."); } public void run3(){ System.out.println("run3 method is executed. . ."); } }
10.3, Test Method
public static void AnnotationTest() { // get class object Class<AnnotationDemo> aClass = AnnotationDemo.class; // get instance object try { AnnotationDemo annotationDemo = aClass.newInstance(); // Get all methods in the target class Method[] methods = aClass.getMethods(); // iterate over all methods for (Method method : methods) { // Determine whether the method has the @MyTest annotation boolean flag = method.isAnnotationPresent(MyTest.class); if (flag) { // If there is this annotation, execute method.invoke(annotationDemo); } } } catch (Exception e) { e.printStackTrace(); } }
Conclusion: The above is the content of this time, which roughly introduces what annotations are, creating annotations, and using annotations. There are deficiencies, the big guys give pointers, come on!