注解(Annotation)的定义及使用

今天学习了java的Annotation部分,这里使用一个简单的小应用总结一下Annotation的定义及使用。
应用场景:假设有一个类Wait4Test中有几个方法需要测试,我们用自定义的注解TestMethod表示需要测试的方法;另外某个标注了TestMethod的方法可能因为一些原因,暂时不需要进行测试,我们用另外一个自定义的注解Ignore进行标注。在TestManager类中识别出所有需要进行测试的方法,并返回。
在Ignore标注时,为了理解忽略测试的原因,所以需要给它传递一些参数:
reason:字符串数组类型,用于表示忽略的原因
author:普通字符串类型,用于表示标注者姓名
date:用另一注解Date表示的自定义注解类型,表示时间

下面是此应用的代码实现:
先定义三个自定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestMethod {

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ignore {
	String[] reason();		//用于接收表示Ignore原因的参数,用数组表示
	String author();		//用于表示设置Ignore的作者
	Date date();			//用于接收设置Ignore注释的时间的参数,该参数调用了另外的一个注解Date
}

public @interface Date {

	int year();
	int month();
	int day();
}


在自定义注解时,使用了另外的两个注解:Target和Retention
Target注解用于设置此处定义的注解使用的位置,各种可取值在ElementType中定义
Retention注解用于设置此处定义的注解的保留期限,包括了三种不同的类型:
  Source:此注解仅在源码级别有效,编译时会被丢弃
  Class:保存在类文件中,在运行时会被丢弃
  Runtime:保存在类文件中,在运行时由JVM保留

下面的代码是需要进行标注的类,该类的方法定义时使用了我们上面定义的注解:

public class Wait4Test {
	@TestMethod
	public void testA() {

	}

	@TestMethod
	public void testB() {

	}
	
	/**
	 * Ignore注解中使用了多个参数,并且是不同类型的
	 * reason表示了设置数组类型的参数的方式
	 * author表示设置普通参数的方式
	 * date表示了设置另外一种注解表示的参数的方式
	 */
	@Ignore(reason = { "reason1", "reaon2" }, author = "yige", date = @Date(year = 2010, month = 10, day = 7))
	@TestMethod
	public void testC() {

	}
}


下面的代码用于根据注解判断哪些方法需要进行测试:
public class TestManager<T> {

	private Class<T> testClass;

	public TestManager(Class<T> testClass) {
		this.testClass = testClass;
	}
	public List<Method> loadTestMethods() {
		List<Method> testMethods = null;
		if (testClass != null) {
			testMethods = new ArrayList<Method>();
			for (Method method : testClass.getDeclaredMethods()) {
				/**
				 * 通过Method对象的isAnnotationPresent方法判断该方法是否被标注了某种注解
				 */
				if (method.isAnnotationPresent(TestMethod.class)
						&& !method.isAnnotationPresent(Ignore.class)) {
					testMethods.add(method);
				}
			}
		}
		return testMethods;
	}
} 

你可能感兴趣的:(jvm)