关键字@interface 定义一个注解标记。注解也将会编译成class文件。以下定义的为方法注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value=ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MethodAnnotation { public String name(); public int time() default 0; }
定义一个类,方法使用注解。
public class TestCase { public void method(){ System.out.println("method"); } @MethodAnnotation(name="case1", time=10) public void method1(){ System.out.println("method1"); } @MethodAnnotation(name="case2", time=20) public void method2(){ System.out.println("method2"); } }
编写注解处理器:使用反射来遍历方法。
public class TestCaseTracker { public static void printTestCase(Class<?> bindClass){ assert bindClass != null; for (Method method : bindClass.getDeclaredMethods()){ MethodAnnotation bind = method.getAnnotation(MethodAnnotation.class); if (bind == null) continue; // Not found annotation. System.out.println(String.format("Found [%s] Test Case : %s-%d", method .getName(), bind.name(), bind.time())); } } public static void main(String[] args) { TestCaseTracker.printTestCase(TestCase.class); } }
2.元注解
在J2SE中内置了三种常用标准注解(Override, Deprecated, SuppressWarnings)以及四种元注解:
@Target: 表示该注解可以用于什么地方。可用ElementType枚举类型主要有:
TYPE : 类、接口或enum声明
FIELD: 域(属性)声明
METHOD: 方法声明
PARAMETER: 参数声明
CONSTRUCTOR: 构造方法声明
LOCAL_VARIABLE:局部变量声明
ANNOTATION_TYPE:注释类型声明
PACKAGE: 包声明
@ Retention: 表示需要在什么级别保存该注解信息。可用 RetentionPolicy枚举类型主要有:
SOURCE: 注解将被编译器丢弃。
CLASS : 注解在class文件中可能。但会被VM丢弃。
RUNTIME: VM将在运行时也保存注解(如果需要通过反射读取注解,则使用该值)。
@ Documented: 将此注解包含在Javadoc中。
@ Inherited: 允许子类继承父类中的注解。
3.使用技巧
1.如果希望定义的注解用于多种 ElementType 的话可以写成:
import static java.lang.annotation.ElementType @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
2.在声明注解中的方法时可通过 default 来指定默认值。
3.在声明注解中的方法返回类型可结合泛型使用,如:
Class<? extends Payload>[] payload() default {};
4.可在注解类中定义嵌套注解,如:
import static java.lang.annotation.ElementType @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented public @interface NotNull { String message() default "{javax.validation.constraints.NotNull.message}"; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface List { NotNull[] value(); } }
@NotNull.List(value = { @NotNull }) protected List<?> list;
5.在JASE中提供了很少的内置注解,不过JBoss提供了一个 validation-api 的类库,提供常用验证注解。有兴趣的朋友可以下载看看,其 maven 依赖为:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0</version> </dependency>