概述
- 注解:元数据
- 注解本身仅仅是元数据,和业务逻辑无关,业务逻辑是注解的用户来实现的,比如JVM也是这样的一个用户
- 元注解:注解的注解
- @Documented:注解是否包含在Java Doc中
- @Retention:注解生命周期
- RetentionPolicy.SOURCE:编译阶段丢弃,不进入字节码;如Override,SupressWarnings
- RetentionPolicy.CLASS:默认,类加载时丢弃,字节码处理过程中有用
- RetentionPolicy.RUNTIME:始终不丢弃,运行期通过反射获取
- @Target:注解用于什么地方
- 如不明确指出,则该注解可放在任何地方
- ElementType.TYPE:类,接口,或enum
- FIELD
- METHOD
- PARAMETER
- CONSTRUCTOR
- LOCAL_VARIABLE
- ANNOTATION_TYPE:另一个注解
- PACKAGE
- @Inherited:是否允许被子注解继承
例子
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo{
public enum Priority {LOW, MEDIUM, HIGH}
public enum Status {STARTED, NOT_STARTED}
String author() default "Yash";
Priority priority default Priority.LOW;
Status status() default Status.NOT_STARTED;
}
@Todo(priority=Todo.Priority.MEDIUM, author="Yashwant", status=Todo.Status.STARTED)
public void method1() {
// xxx
}
@interface Author {
String value();
}
@Author("Yashwant")
public void method2() {
// xxx
}
注解处理
Class businessLogicClass = BusinessLogic.class;
for(Method method : businessLogicClass.getMethods()) {
Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
if(todoAnnotation != null) {
System.out.println("Method Name: " + method.getName());
System.out.println("Author: " + todoAnnotation.author());
System.out.println("Priority: " + todoAnnotation.priority());
System.out.println("Status: " + todoAnnotation.status());
}
}
网友评论