首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

自定义 Java Annotation及运用

2012-12-25 
自定义 Java Annotation及应用作为一个Javaer 我想对于 Java Annotation(注解或元数据)并已不是什么新鲜的

自定义 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;}

       以上是一个用于Method级的简单的@Bind注解类,比较有点象接口的结构,事实上,与其它任何Java接口一样,注解也将会编译成class文件。
      
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..}}


编写注解处理器:
     在 JASE 1.5扩展了了反射机制的API,为我们提供了相应的注解处理器的API,另外还可以通过外部工具 apt 来解析带有注解的Java Code.
   
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*///~


  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. 使用技巧
           a. 如果希望定义的注解用于多种  ElementType 的话可以写成:
import static java.lang.annotation.ElementType@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })

           b. 在声明注解中的方法时可通过 default 来指定默认值。
           c.  在声明注解中的方法返回类型可结合泛型使用,如:
Class<? extends Payload>[] payload() default {};

           d. 可在注解类中定义嵌套注解,如:
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;

        e. 在JASE中提供了很少的内置注解,不过JBoss提供了一个 validation-api 的类库,提供常用验证注解。有兴趣的朋友可以下载看看,其 maven 依赖为:
<dependency>  <groupId>javax.validation</groupId>  <artifactId>validation-api</artifactId>  <version>1.0</version></dependency>

热点排行