“This is the 13th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021”.
Simple introduction
Annotations are used a lot in development these days. For example, @Controller and so on, but custom annotations are also sometimes encountered, such as in the company’s logging during development. Being a scumbag ape still makes it necessary to learn custom annotations.
In this article we will start with a simple annotation example, and will not immediately introduce various meta-annotations. Get a feel for annotations from examples
Define a comment
package com.kevin.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Kevin {
String name() default "kevin";
}
Copy the code
Parse and test the annotation
package com.kevin;
import com.kevin.annotation.Kevin;
@Kevin
public class Test {
public static void showKevin(Class c) {
System.out.println(c.getName());
boolean isExist = c.isAnnotationPresent(Kevin.class);
if(isExist) { Kevin kevin = (Kevin) c.getAnnotation(Kevin.class); System.out.println(kevin.name()); }}public static void main(String[] args) { Test.showKevin(Test.class); }}Copy the code
The results
com.kevin.Test
kevin
Process finished with exit code 0
Copy the code
conclusion
In the last few lines of code, we have implemented a simple custom annotation. You don’t want to think about annotations too complicated, in fact, anything large scale application must be easy to understand.
A simple introduction
The overall graphic
Built-in annotations
@override Override
This annotation should be used often when subclasses overwrite parent methods, such as the toString() method
package com.kevin.demo; public class Demo1 { @Override public String toString(){ return "demo1"; }}Copy the code
@ Deprecated outdated
Deprecated can be Deprecated for a wide range of classes, methods, fields, parameters, etc. It indicates that the corresponding code is obsolete and should not be used by programmers. However, it is a warning, not mandatory.
package com.kevin.demo; Public class Demo1 {@deprecated public void goHome(){system.out.println (" obsolete method "); }}Copy the code
Idea calls these methods and the compiler also displays a delete line with a warning
@suppressWarning Suppresses Java compilation warnings
@SuppressWarnings suppresses Java compile warnings, which has a mandatory parameter indicating which type of warning to suppress.
The keyword | use |
---|---|
all | to suppress all warnings |
boxing | to suppress warnings relative to boxing/unboxing operations |
cast | to suppress warnings relative to cast operations |
dep-ann | to suppress warnings relative to deprecated annotation |
deprecation | to suppress warnings relative to deprecation |
fallthrough | to suppress warnings relative to missing breaks in switch statements |
finally | To suppress warnings relative to finally block that Don ¡ ¯ t return |
hiding | to suppress warnings relative to locals that hide variable |
incomplete-switch | to suppress warnings relative to missing entries in a switch statement (enum case) |
nls | to suppress warnings relative to non-nls string literals |
null | to suppress warnings relative to null analysis |
rawtypes | to suppress warnings relative to un-specific types when using generics on class params |
restriction | to suppress warnings relative to usage of discouraged or forbidden references |
serial | to suppress warnings relative to missing serialVersionUID field for a serializable class |
static-access | to suppress warnings relative to incorrect static access |
synthetic-access | to suppress warnings relative to unoptimized access from inner classes |
unchecked | to suppress warnings relative to unchecked operations |
unqualified-field-access | to suppress warnings relative to field access unqualified |
unused | to suppress warnings relative to unused code |
The above method, we can increase
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
demo1.goHome();
}
Copy the code
Yuan notes
Meta-annotations: Annotations of annotations, which are specially prepared by Java for annotation development.
Let’s take a look at Java meta-annotations using @Override, the built-in Java annotation mentioned above
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Copy the code
@Target
The @target is the Target of the annotation. The @override Target is the METHOD (ElementType.METHOD). ElementType is an enumeration.
- TYPE: Represents a class, interface (including annotations), or enumeration declaration
- FIELD: FIELD, including enumerated constants
- METHOD: the METHOD
- PARAMETER: PARAMETER in a method
- (4) CONSTRUCTOR
- LOCAL_VARIABLE: local variable
- ANNOTATION_TYPE: Annotation type
- PACKAGE: a PACKAGE
There can be multiple targets, represented by {}. For example, @suppressWarnings has multiple @targets, defined as:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
Copy the code
If there is no declaration@Target
Defaults to apply to all types. The demo of our previous article did not declare it@Target
@Retention
@retention Indicates how long the annotation information is retained. The value can have only one value. The type is RetentionPolicy, which is an enumeration with three values:
SOURCE
: is retained only in the source code, and is discarded when the compiler compiles the code into a bytecode fileCLASS
: reserved to bytecode files, but not necessarily retained in memory when the Java virtual machine loads the class file into memoryRUNTIME
: reserved until run time
If @Retention is not stated, it defaults to CLASS.
@Override and @SuppressWarnings are both used by the compiler, so @Retention is both retentionPolicy.source.
@Documented
Use to specify that the annotation information is displayed when Javadoc generates API documents. Documented is a marked annotation that has no member.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
Copy the code
@Inherited
An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited.
Watch a chestnut
public class Demo1 {
@Inherited
@Retention(RetentionPolicy.RUNTIME)
static @interface Test {
}
@Test
static class Base {
}
static class Child extends Base {
}
public static void main(String[] args) {
System.out.println(Child.class.isAnnotationPresent(Test.class));
}
}
Copy the code
The main method checks if the Child class has a Test annotation, and the output is true, because Test has the @inherited annotation. When this is left out, the output is false