参考教材地址
http://wiki.jikexueyuan.com/project/java-reflection/java-at.html
注解的定义与接口的定义相似,下面是MyAnnotation注解的定义:
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
//@Target(ElementType.TYPE)
public @interface MyAnnotation {
public String name();
public String value();
}
类注解
package annotation;
@MyAnnotation(name = "someName",value = "Hello Word")
public class TheClass {
}
package annotation;
public class TwoClass {
@MyAnnotation(name = "twoName",value = "Hello Two")
public void doSomething(){}
}
main方法
package annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Demo1 {
public static void main(String[] args) {
Class aClass = TheClass.class;
//指定访问所有类的注解
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation:annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation annotation2 = (MyAnnotation) annotation;
System.out.println("name:" + annotation2.name());
System.out.println("value:" + annotation2.value());
}
}
System.out.println("---------------------");
//指定访问一个类的注解
Class bClass = TheClass.class;
Annotation myAnnotation = bClass.getAnnotation(MyAnnotation.class);
if (myAnnotation instanceof MyAnnotation) {
MyAnnotation annotation2 = (MyAnnotation) myAnnotation;
System.out.println("name:" + annotation2.name());
System.out.println("value:" + annotation2.value());
}
System.out.println("---------------------");
try {
Method method = TwoClass.class.getMethod("doSomething");
Annotation[] annotations2 = method.getDeclaredAnnotations();
//Annotation annotation = method.getAnnotation(MyAnnotation.class);获取指定方法的注解
for (Annotation annotation:annotations2) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation2 = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation2.name());
System.out.println("value: " + myAnnotation2.value());
}
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}