一要定义注解(第三方提供)
二要使用注解(我们就使用)
三要反射注解(框架读取它)
注意:
反射注解的要求是注解的保密策略必须是RUNTIME
反射注解需要从作用目标上返回
1、类上的注解需要使用Class来获取
2、方法上的注解需要使用Method来获取
3、构造器上的注解需要使用Construcator来获取
4、成员上的注解需要使用Field来获取
package 反射注解;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
// 获取类上的注解
@org.junit.Test
public void fun1() {
/*
* 1.得到作用对象
*/
Class<A> class1 = A.class;
/*
* 2.获取指定类型的注解
*/
MyAnnol myAnnol = class1.getAnnotation(MyAnnol.class);
// 如果定义注解时不写// @Retention(RetentionPolicy.RUNTIME)就会null
System.out.println("myAnnol是否为空呢?" + myAnnol);
System.out.println(myAnnol.name() + "," + myAnnol.age() + ","
+ myAnnol.sex());
}
// 获取方法上的注解
@org.junit.Test
public void fun2() throws NoSuchMethodException, SecurityException {
// 1.得到作用目标
Class<A> class1 = A.class;
Method method = class1.getMethod("fun1");
// 2.获取指定方法的注解
MyAnnol myAnnol = method.getAnnotation(MyAnnol.class);
System.out.println(myAnnol.name() + ", " + myAnnol.age() + ", "
+ myAnnol.sex());
}
// 获取构造器上的注解
@org.junit.Test
public void fun3() throws NoSuchMethodException, SecurityException {
// 1.得到作用目标
Class<A> class1 = A.class;
Constructor<A> constructor = class1.getConstructor(A.class);
// 2.获取指定构造器的注解
MyAnnol myAnnol = constructor.getAnnotation(MyAnnol.class);
constructor.setAccessible(true);
System.out.println(myAnnol.name() + ", " + myAnnol.age() + ", "
+ myAnnol.sex());
}
// 获取成员变量上的注解
@org.junit.Test
public void fun4() throws NoSuchFieldException, SecurityException {
// 1.得到作用目标
Class<A> class1 = A.class;
Field field = class1.getField("string");
// 2.获取指定成员变量上的注解
MyAnnol myAnnol = field.getAnnotation(MyAnnol.class);
// field.setAccessible(true);//可以访问私有变量
System.out.println(myAnnol.name() + ", " + myAnnol.age() + ", "
+ myAnnol.sex());
}
}
// 注解使用在类上
@MyAnnol(name = "A类", age = 1, sex = "男")
class A {
// 注解使用在成员变量上
@MyAnnol(name = "成员变量", age = 0, sex = "女")
public String string;// 定义为public就可以使用,定义为priavate的话要field.setAccessible(true);
// 注解使用在成员方法上
@MyAnnol(name = "fun1方法", age = 2, sex = "女")
public void fun1() {
}
// 注解使用在构造器上
@MyAnnol(name = "无参构造器", age = 3, sex = "男")
public A() {
}
}
// 定义注解(要使用一个枚举元注解)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnol {
String name();
int age();
String sex();
}
原文:http://blog.csdn.net/u012110719/article/details/46398947