java 注解(自身理解)

声明注解

使用注解

解析注解

产生的结果

注解利用的是反射机制

 =============================================================

使用注解修饰了类/方法/成员变量等之后,这些注解不会自己生效,必须由这些注解的开发者提供相应的工具来提取并处理注解信息(当然,只有当定义注解时使用了@Retention(RetentionPolicy.RUNTIME)修饰,JVM才会在装载class文件时提取保存在class文件中的注解,该注解才会在运行时可见,这样我们才能够解析).
Java使用Annotation接口来代表程序元素前面的注解,该接口是所有注解的父接口。
java5在java.lang.reflect包下新增了 用AnnotatedElement接口代表程序中可以接受注解的程序元素.
AnnotatedElement接口的实现类有:Class(类元素)、Field(类的成员变量元素)、Method(类的方法元素)、Package(包元素),每一个实现类代表了一个可以接受注解的程序元素类型。
这样, 我们只需要获取到Class、 Method、 Filed等这些实现了AnnotatedElement接口的类的实例,通过该实例对象调用该类中的方法(AnnotatedElement接口中抽象方法的重写) 就可以获取到我们想要的注解信息了。

获得Class类的实例有三种方法:
(1)利用对象调用getClass()方法获得Class实例
(2)利用Class类的静态的forName()方法,使用类名获得Class实例
(3)运用.class的方式获得Class实例,如:类名.class

AnnotatedElement接口提供的抽象方法(在该接口的实现类中重写了这些方法):
1. <T extends Annotation> T getAnnotation(Class<T> annotationClass)
<T extends Annotation>为泛型参数声明,表明A的类型只能是Annotation类型或者是Annotation的子类。
功能:返回该程序元素上存在的、指定类型的注解,如果该类型的注解不存在,则返回null
2. Annotation[] getAnnotations()
功能:返回此元素上存在的所有注解,包括没有显示定义在该元素上的注解(继承得到的)。(如果此元素没有注释,则返回长度为零的数组。)
3. <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass)
功能:这是Java8新增的方法,该方法返回直接修饰该程序元素、指定类型的注解(忽略继承的注解)。如果该类型的注解不存在,返回null.
4. Annotation[] getDeclaredAnnotations()
功能:返回直接存在于此元素上的所有注解,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)
5. boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
功能:判断该程序元素上是否存在指定类型的注解,如果存在则返回true,否则返回false。
6. <T extends Annotation> T[] getAnnotationsByTpye(Class<T> annotationClass)
功能: 因为java8增加了重复注解功能,因此需要使用该方法获得修饰该程序元素、指定类型的多个注解。
7. <T extends Annotation> T[] getDeclaredAnnotationsByTpye(Class<T> annotationClass)
功能: 因为java8增加了重复注解功能,因此需要使用该方法获得直接修饰该程序元素、指定类型的多个注解。
Class提供了getMethod()、getField()以及getConstructor()方法(还有其他方法),这些方法分别获取与方法、域变量以及构造函数相关的信息,这些方法返回Method、Field 以及Constructor类型的对象。

@Target(ElementType.Method)
@Retention(RetentionPopicy.RUNTIME)
public @interface MyTag
{
string name() default "yeeku";
int age() default 32;
}

public class Test
{
@MyTag
public void info()
{

}
}

获取Test类的info方法里的所有注解,并打印这些注解
Annotation [] aArray=Class.forName("Test").getMethod("info").getAnnotations(); //获取Class实例的方法1
for(Annotation an : aArray)
{
system.out.println(an);
}

如果需要获取某个注解里的元数据则可以将注解强制类型转换,转换成所需的注解类型,然后通过注解对象的抽象方法来访问这些元数据
获取tt对象的info方法所包含的所有注解
Annotation [] annotation=tt.getClass().getMethod("info").getAnnotations(); //获取Class实例的方法2
for(Annotation tag : annotation)
{
//如果tag注解是MyTag类型
system.out.println("tag.name(): "+((MyTag)tag).name());
system.out.println("tag.age(): "+((MyTag)tag).age());
}

声明注解还不能用,为了让程序中的这些注解起作用,必须为这些注解提供一个注解处理工具

原文地址:https://www.cnblogs.com/austinspark-jessylu/p/6375061.html