Java自定义注解的定义与使用

跟踪代码的依赖性,实现代替配置文件的功能。比较常见的是 Spring 等框架中的基于注解配置。

登陆、权限拦截、日志处理,以及各种 Java 框架,如 Spring,Hibernate,JUnit 。提到注解就不能不说反射,Java 自定义注解是通过运行时靠反射获取注解。实际开发中,例如我们要获取某个方法的调用日志,可以通过 AOP(动态代理机制)给方法添加切面,通过反射来获取方法包含的注解,如果包含日志注解,就进行日志记录。

 

注解是 Java 1.5 引入的,目前已被广泛应用于各种 Java 框架,如 Hibernate,Jersey,Spring。注解相当于是一种嵌入在程序中的元数据,可以使用注解解析工具或编译器对其进行解析,也可以指定注解在编译期或运行期有效。

在注解诞生之前,程序的元数据存在的形式仅限于 java 注释或 javadoc,但注解可以提供更多功能,它不仅包含元数据,还能作用于运行期,注解解析器能够使用注解决定处理流程。举个例子,在Jersey webservice中,我们在一个方法上添加了 PATH 注解和 URI 字符串,在运行期,jersey 会对其进行解析,并决定作用于指定 URI 模式的方法。

 

在 Java 中创建自定义注解

创建自定义注解与编写接口很相似,除了它的接口关键字前有个 @符号。我们可以在注解中定义方法,先来看个例子,之后我们会继续讨论它的特性。

package com.journaldev.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
String author()
default "Pankaj";
String date();
int revision() default 1;
String comments();
}

  • 注解方法不能有参数。
  • 注解方法的返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组。
  • 注解方法可以包含默认值。
  • 注解可以包含与其绑定的元注解,元注解为注解提供信息,有四种元注解类型:

1. @Documented – 表示使用该注解的元素应被 javadoc 或类似工具文档化,它应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了 Documented 注解,那么它的注解会成为被注解元素的公共 API 的一部分。

2. @Target – 表示支持注解的程序元素的种类,一些可能的值有 TYPE, METHOD, CONSTRUCTOR, FIELD 等等。如果 Target 元注解不存在,那么该注解就可以使用在任何程序元素之上。

3. @Inherited – 表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层(Object)。

4. @Retention – 表示注解类型保留时间的长短,它接收 RetentionPolicy 参数,可能的值有 SOURCE, CLASS, 以及 RUNTIME。

Java 内置注解

Java 提供 3 种内置注解。

1. @Override – 当我们想要覆盖父类的一个方法时,需要使用该注解告知编译器我们正在覆盖一个方法。这样的话,当父类的方法被删除或修改了,编译器会提示错误信息。大家可以学习一下为什么我们总是应该在覆盖方法时使用Java 覆盖注解

2. @Deprecated – 当我们想要让编译器知道一个方法已经被弃用 (deprecate) 时,应该使用这个注解。Java 推荐在 javadoc 中提供信息,告知用户为什么这个方法被弃用了,以及替代方法是什么。

3. @SuppressWarnings – 这个注解仅仅是告知编译器,忽略它们产生了特殊警告,比如:在java 泛型中使用原始类型。它的保持性策略 (retention policy) 是 SOURCE,在编译器中将被丢弃。

我们来看一个例子,展示了如何使用内置注解,以及上述示例中提及的自定义注解。

package com.journaldev.annotations;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class AnnotationExample {

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
}

@Override
@MethodInfo(author </span>= "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String toString() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "Overriden toString method"<span style="color: rgba(0, 0, 0, 1)">;
}

@Deprecated
@MethodInfo(comments </span>= "deprecated method", date = "Nov 17 2012"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> oldMethod() {
    System.out.println(</span>"old method, don't use it."<span style="color: rgba(0, 0, 0, 1)">);
}

@SuppressWarnings({ </span>"unchecked", "deprecation"<span style="color: rgba(0, 0, 0, 1)"> })
@MethodInfo(author </span>= "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span> genericsTest() <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> FileNotFoundException {
    List l </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> ArrayList();
    l.add(</span>"abc"<span style="color: rgba(0, 0, 0, 1)">);
    oldMethod();
}

}

我相信这个例子是很明了的,展示了不同场景下注解的使用方式。

Java 注解解析

我们将使用 Java 反射机制从一个类中解析注解,请记住,注解保持性策略应该是 RUNTIME,否则它的信息在运行期无效,我们也不能从中获取任何数据。

package com.journaldev.annotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationParsing {

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Method method : AnnotationParsing.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">
                .getClassLoader()
                .loadClass((</span>"com.journaldev.annotations.AnnotationExample"<span style="color: rgba(0, 0, 0, 1)">))
                .getMethods()) {
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> checks if MethodInfo annotation is present for the method</span>
            <span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (method
                    .isAnnotationPresent(com.journaldev.annotations.MethodInfo.</span><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">)) {
                </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
                    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> iterates all the annotations available in the method</span>
                    <span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (Annotation anno : method.getDeclaredAnnotations()) {
                        System.out.println(</span>"Annotation in Method '"
                                + method + "' : " +<span style="color: rgba(0, 0, 0, 1)"> anno);
                    }
                    MethodInfo methodAnno </span>=<span style="color: rgba(0, 0, 0, 1)"> method
                            .getAnnotation(MethodInfo.</span><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
                    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (methodAnno.revision() == 1<span style="color: rgba(0, 0, 0, 1)">) {
                        System.out.println(</span>"Method with revision no 1 = "
                                +<span style="color: rgba(0, 0, 0, 1)"> method);
                    }

                } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Throwable ex) {
                    ex.printStackTrace();
                }
            }
        }
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span> (SecurityException |<span style="color: rgba(0, 0, 0, 1)"> ClassNotFoundException e) {
        e.printStackTrace();
    }
}

}

以上程序的输出是:

Annotation in Method 'public java.lang.String com.journaldev.annotations.AnnotationExample.toString()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=Main method, date=Nov 17 2012)
Method with revision no 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=deprecated method, date=Nov 17 2012)
Method with revision no 1 = public static void com.journaldev.annotations.AnnotationExample.oldMethod()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.genericsTest()throws java.io.FileNotFoundException' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=10, comments=Main method, date=Nov 17 2012)

注解 API 非常强大,被广泛应用于各种 Java 框架,如 Spring,Hibernate,JUnit。可以查看《Java 中的反射》获得更多信息。

 

转载地址:http://www.importnew.com/14479.html