自定义 Java Annotation及应用
作为一个Javaer 我想对于 Java Annotation(注解或元数据)并已不是什么新鲜的东西了,在现在流行的SSH、JUnit等框架中早也已经广泛使用,然而在我们实际开发中对于自定义 Annotation 的场景和需求也并不见得多,大多数都还是以使用为主。
1. 基本语法
package org.denger.annotation.example;import java.lang.annotation.ElementType;import java.lang.annotation.Target;// The @Bind tag.@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Bind { public String name(); public int time() default 0;}package org.denger.annotation.example;/** * Use the @Bind tag. */public class BindCase {@Bind(name="case", time=1)public void method(){// do something..}public void method1(){// do something..}@Bind(name="case1", time=20)public void method2(){// do something..}}public class BindCaseTracker{private static Logger logger = Logger.getLogger(BindCaseTracker.class);public static void printBindCase(Class<?> bindClass){assert bindClass != null;for (Method method : bindClass.getDeclaredMethods()){Bind bind = method.getAnnotation(Bind.class);if (bind == null) continue; // Not found annotation.logger.debug(String.format("Found [%s] Bind Case : %s-%d", method.getName(), bind.name(), bind.time()));}}public static void main(String[] args) {BindCaseTracker.printBindCase(BindCase.class);}} /* Output:[DEBUG] 11-08 14:15 Found [method] Bind Case : case-1[DEBUG] 11-08 14:15 Found [method2] Bind Case : case1-20*///~import static java.lang.annotation.ElementType@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })Class<? extends Payload>[] payload() default {};import static java.lang.annotation.ElementType@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)@Documentedpublic @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;<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0</version></dependency>