Annotations

 

/**定义该注解能使用的位置,如今表示同在方法上**/
/**
 * ElementType下还包括:
 * CONSTRUCTOR:构造函数声明;
 * FIELE:属性声明,包括枚举;
 * LOCAL_VARIABLE:本地变量
 * PACKAGE:包级别
 * PARAMETER:参数级别
 * TYPE:类、接口(包括注解本身自己)、枚举
 */
@Target(value = { ElementType.METHOD })
/**定义该注解可用范围,如今表示在运行时可用**/
/**
 *RetentionPolicy还包括:
 *SOURCE:注解只在编译器有效
 *CLASS:只活动在编译器的class文件里,jvm时期就无效
 *RUNTIME:运行时jvm仍然保持着,可以反射获得
 */
@Retention(RetentionPolicy.RUNTIME)
/**
 *除了以上两个注解还有两个:
 *@Documented:生成文档时也一块儿带到文档中去
 *@Inherted:容许子类继承父类的注解
 */
/**注解不容许继承 不能 extends @interface**/
public @interface Test {
	/**注解元素不容许使用包装类型**/
	public int id();
	public String description() default "no description";
}



public class UseAnnotation {
	public static void main(String[] args) {
		Class<?> clazz = AddAnnotation.class;
		Method [] ms = clazz.getDeclaredMethods();
		for(Method m : ms) {
			Test t = m.getAnnotation(Test.class);
			if(null != t) {
				System.out.println(t.id()+t.description());
			}
		}
	}
}
class AddAnnotation {
	@Test(id=10)
	public void method() {
		
	}
	@Test(id=11,description="method2")
	public void mehtod2() {
		
	}
	/**也能够声明在方法参数上!!而且不用@Test**/
	public void method3(Test test) {
		if(test.id()==10) {
		}
	}
}
相关文章
相关标签/搜索