通常,应用程序并不是必须定义annotation类型,但是定义annotation类型并非难事。
Annotation类型声明与一般的接口声明极为类似,区别只在于它在interface关键字前面使用”@“符号。
Annotation类型的每个方法声明定义一个annotation类型成员,但方法声明不必有参数或异常声明;
方法返回值类型被限制在以下范围:private、String、Class、enums、annotation和前面类型的数组;方法可以有默认值。
一个简单的annotation类型声明:
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
代码中只定义一个annotation类型RequestForEnhancement
修饰方法的annotation声明方式:
annotation是一种修饰符,能够和其它修饰符(如public、static、final)一般使用。
习惯用法是annotation用在其它修饰符前面。
annotation有"@+annotation类型+带有括号的成员-值列表"组成。
这些成员的值必须是编译时常量(即在运行时不变)。
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
一个使用了RequestForEnhancement annotation的方法声明
/// ///
声明一个没有成员的annotation类型,可使用以下方式:
public @interface Preliminary { }
作为上面没有成员的annotation类型声明的简写方式:
@Preliminary public class TimeTravel { ... }
/// ///
如果在annotation中只有唯一一个成员,则该成员应命名为valua:
public @interface Copyright {
String value();
}
更为方便的是对于具有唯一成员且成员名为value的annotation(如上文),在其使用时可以忽略掉成员名和赋值号(=)
@Copyright("2002 Wei.peng Test System")
public class OscillationOverthruster { ... }
/// ///
一个使用实例
基于annotation测试框架:
首先需要annotation类型来表示某个方法是一个应该被测试工具运行的测试方法
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
值得注意的是annotation类型声明是可以标注自己的,这样的annotation被称为”meta-annotation“。
在上面的代码中,@Retention(RetentionPolicy.RUNTIME)这个meta-annotation表示了此类型的 annotation将被虚拟机保留使其能够在运行时通过反射被读取。而@Target(ElementType.METHOD)表示此类型的 annotation只能用于修饰方法声明。
一个简单的程序,其中部分方法被上面的annotation所标注
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;
public class RunTests {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}
这 个程序从命令行参数中取出类名,并且遍历此类的所有方法,尝试调用其中被上面的测试annotation类型标注过的方法。在此过程中为了找出哪些方法被 annotation类型标注过,需要使用反射的方式执行此查询。如果在调用方法时抛出异常,此方法被认为已经失败,并打印一个失败报告。最后,打印运行 通过/失败的方法数量。
下面文字表示了如何运行这个基于annotation的测试工具:
$ java RunTests Foo Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash Passed: 2, Failed 2
/// ///
Annotation分类
1、内建Annotation---Java5.0版在java语法中经常用到的内建Annotation
@Deprecated 用于修饰已经过时的方法
@Override 用于修饰此方法覆盖了父类的方法(而非重载)
@SuppressWarning 用于通知java编译器禁止特定的编辑警告
import java.util.List;
public class UsingBuiltInAnnotation {
//食物类
class Food{}
//干草类
class Hay extends Food{}
//动物类
class Animal{
Food getFood(){
return null;
}
//使用Annotation声明Deprecated方法
@Deprecated
void deprecatedMethod(){
}
}
//马类-继承动物类
class Horse extends Animal{
//使用Annotation声明覆盖方法
@Override
Hay getFood(){
return new Hay();
}
//使用Annotation声明禁止警告
@SuppressWarnings({"deprecation","unchecked"})
void callDeprecatedMethod(List horseGroup){
Animal an=new Animal();
an.deprecatedMethod();
horseGroup.add(an);
}
}
}
2、开发者自定义Annotation,由开发者自定义Annotation类型
3、使用第三方开发的Annotation类型
开发人员所常常用到的一种方式,比如我们使用Hibernate3.0时就可以利用Annotaion生成数据表映射配置文件。