@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TypeAnnotation {
String value() default "这是类注解";
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodAnnotation {
String value() default "这是方法注解";
}
此处通过反射拿到类对象,获取注解,来操作。
再生产中也可以结合切面编程来处理注解,或者扫描指定包下的所有类,遍历处理注解
public class AnnotationHandler {
public static void main(String[] args){
//可以配置扫描路径加载所有class,也可以使用aspectj直接做前面处理
Class aClass = null;
try {
aClass = Class.forName("annotation.TestAnnotation");
TypeAnnotation annotation = (TypeAnnotation)aClass.getAnnotation(TypeAnnotation.class);
if(annotation != null){
System.out.println(annotation.value());
}
Method[] declaredMethods = aClass.getDeclaredMethods();
for(Method method:declaredMethods){
MethodAnnotation methodAnnotation = method.getAnnotation(MethodAnnotation.class);
if(methodAnnotation != null){
System.out.println(methodAnnotation.value());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
这个注解表明自定义注解的适用范围,值为一个ElementType数组,ElementType有以下值
TYPE:类、接口(包括注解类型)和枚举的声明
FIELD:字段声明(包括枚举常量)
METHOD:方法声明
PARAMETER:参数声明
CONSTRUCTOR:构造函数声明
LOCAL_VARIABLE:本地变量声明
ANNOTATION_TYPE:注解类型声明
PACKAGE:包声明
TYPE_PARAMETER:类型参数声明,JavaSE8引进,可以应用于类的泛型声明之处
TYPE_USE:任何类型都可以添加注解
注释的保留策略,值为一个RetentionPolicy数组,有以下值
SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;