反编译注解类可看到注解的本质:继承Annotation接口的接口。
元注解:描述注解的注解。https://www.cnblogs.com/kingsonfu/p/10634174.html
元注解有@Target注解的值包括ElementType.ANNOTATION_TYPE。
/**
* The constants of this enumerated type provide a simple classification of the
* syntactic locations where annotations may appear in a Java program.
* 此枚举类型的常量提供了Java程序中注释可能出现的语法位置
* ...
*/
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
// 获取Class、Field、Method的注解,返回Annotation[]
getAnnotations()
// Class、Field、Method是否有某一个注解
clazz.isAnnotationPresent(Controller.class)
// 获取方法参数的注解
Annotation[][] annotations= method.getParameterAnnotations();
// 获取注解的属性值
Autowired autowired = field.getAnnotation(Autowired.class);
String autowiredValueValue = autowired.value();
注解括号中直接写值,默认是value属性的值。属性的类型可以是:基本数据类型、String、枚举、Class、注解及他们的一维数组。
/**
* @Author: ZhangHao
* @Description: 注解测试
* @Date: 2020/8/30 8:22
* @Version: 1.0
*/
@Annotation1("A")
@Annotation2(value="A", name={"1", "2"})
@Annotation3(enumValue = ElementType.ANNOTATION_TYPE)
@Annotation4(annotaionValue = @Annotation1("A"))
public class AnnotationTest {
public static void main(String[] args) {
}
}
@interface Annotation1{
String value();
}
@interface Annotation2{
String[] name();
String value();
}
@interface Annotation3{
ElementType enumValue();
}
@interface Annotation4{
Annotation1 annotaionValue();
}