1 什么是annotation
annotation是java编译器支持的一种标记,它可以简化我们的代码,使得我们的代码更加方便被理解。
2 元annotation
用来编写其它注解的注解。
@Retention
保留期,有三种保留期。
RetentionPolicy.SOURCE
这样的注解只在源码阶段保留,编译器在编译的时候会忽略掉它们。
RetentionPolicy.CLASS
编译的时候会用到它们,但是不会加载到虚拟机中。
RetentionPolicy.RUNTIME
保留到程序运行的时候,并且加载到虚拟机中,在程序运行的时候可以通过反射获取它们。
@Documented
将注解中的元素加载到javadoc中去。
@Target
指的是注解可以生效的地方,有8种。ElementType.ANNOTATION_TYPE、ElementType.CONSTRUCTOR、ElementType.FIELD、ElementType.LOCAL_VARIABLE、
ElementType.METHOD、ElementType.PACKAGE、ElementType.PARAMETER、ElemenType.TYPE。
@Inherited
指的是子类继承超类的注解。
@Repeatable
可以多次使用。
3 注解定义的一般形式
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
int id();
String msg();
}
4 带成员变量的注解
4.1 定义带成员变量的注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
// 定义两个成员变量,注解的成员变量的定义以方法的形式来定义。
String name();
int age default 32;
}
4.2 带成员变量的注解的使用
public class Test {
@MyTag(name = "Dhello")
public void info(){}
}
5 注解的提取和使用
5.1 使用的技术
反射。
5.2 判断是否使用了注解
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}
5.3 获取指定的注解
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}
5.4 获取所有的注解
public Annotation[] getAnnotations() {}
4.5 使用案例
如下例子所示,我们可以获取类上的注解、方法上的注解以及类的成员变量上的注解(该例子来自于网络)。
@TestAnnotation(msg="hello")public class Test { @Check(value="hi") int a; @Perform public void testMethod(){} @SuppressWarnings("deprecation") public void test1(){ Hero hero = new Hero(); hero.say(); hero.speak(); } public static void main(String[] args) { boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class); if ( hasAnnotation ) { TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class); //获取类的注解 System.out.println("id:"+testAnnotation.id()); System.out.println("msg:"+testAnnotation.msg()); } try { Field a = Test.class.getDeclaredField("a"); a.setAccessible(true); //获取一个成员变量上的注解 Check check = a.getAnnotation(Check.class); if ( check != null ) { System.out.println("check value:"+check.value()); } Method testMethod = Test.class.getDeclaredMethod("testMethod"); if ( testMethod != null ) { // 获取方法中的注解 Annotation[] ans = testMethod.getAnnotations(); for( int i = 0;i < ans.length;i++) { System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName()); } } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } }