一.
我们定义的所有annotation都继承于java.lang.annotation.Annotation接口
二.
如果我们通过手工的方式来声明一个接口,让该接口继承Annotation接口,
那么我们定义的这个接口仅仅是一个普通的接口而已,与注解没有任何关系public interface I extends Annotation......仅仅是定义一个接口,而不是注解
三.
java.lang.annotation.Annotation就是一个接口,它本身并不是注解
四.
介绍:Retention及RetentionPolicy与反射的结合在Annotation中的应用
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)//编译程序将Annotation存储于class文件中,可由VM读取
public @interface MyAnnotation {
String hello();
String world();
}
public class MyTest {
@MyAnnotation(hello="beijing",world="shanghai")
@Deprecated
@SuppressWarnings("unchecked")
public void output(){
System.out.println("output something");
}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class MyReflection {
public static void main(String[] args) throws Exception {
MyTest myTest = new MyTest();
Class<MyTest> c = MyTest.class;
Method method = c.getMethod("output", new Class[] {});
if (method.isAnnotationPresent(MyAnnotation.class)) {// 判断此注解是否存在此元素(方法)上
method.invoke(myTest, new Object[] {});// 执行指定对象上的方法
// 获取指定元素(方法)上注解(返回指定的注解或者返回null)
MyAnnotation myAnnotation = method
.getAnnotation(MyAnnotation.class);
String hello = myAnnotation.hello();// 获取注解的属性值
String world = myAnnotation.world();
System.out.println(hello);
System.out.println(world);
}
Annotation[] annotations = method.getAnnotations();// 返回此元素上所有的注解
for (Annotation annotation : annotations) {
// 返回此注解的注解类型
System.out.println(annotation.annotationType().getName());
}
}
}
五.
Class Constructor Field Method Package等类别,都实现了AnnotatedElement接口