如何在运行期间获取注解相关的数据,下面是个示例
首先定义一个注解,该注解在运行期间有效且支持适用于字段和方法:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyAnimation {
String name() default "default name";
}
定义一个类
public class TestAnnotation {
@MyAnimation(name = "realFieldName")
private String mField;
public static void main(String[] args) {
printContainMyAnimationMethodInfo();
print("=======================");
printContainMyAnimationFieldInfo();
}
private static void printContainMyAnimationMethodInfo() {
Class clazz = TestAnnotation.class;
//获取TestAnnotation类所有方法(包括super类)
Method[] methods = clazz.getDeclaredMethods();
if (methods != null) {
for (Method method : methods) {
//判断方法是否包含了指定注解类型
if (method.isAnnotationPresent(MyAnimation.class)) {
print("methodName:" + method.getName());
print(method.getName() + "方法包含MyAnnotation注解 其数据如下");
//获取方法包含指定类型的注解对象
MyAnimation myAnnotation = method.getAnnotation(MyAnimation.class);
String name = myAnnotation.name();
print("name:" + name);
}
}
}
}
private static void printContainMyAnimationFieldInfo() {
////获取TestAnnotation类所有成员变量(包括super类)
Field[] fields = TestAnnotation.class.getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
//判断成员变量是否包含了指定注解类型
if (field.isAnnotationPresent(MyAnimation.class)) {
print("fieldName:" + field.getName());
print(field.getName() + "字段包含MyAnnotation注解其数据如下:");
//获取成员变量包含指定类型的注解对象
MyAnimation annotation = field.getAnnotation(MyAnimation.class);
print("name:" + annotation.name());
}
}
}
}
@MyAnimation(name = "realName")
public static void testAnimationMethod() {
}
public static void print(String msg) {
System.out.println(msg);
}
}
看打印结果
methodName:testAnimationMethod
testAnimationMethod方法包含MyAnnotation注解 其数据如下
name:realName
=======================
fieldName:mField
mField字段包含MyAnnotation注解其数据如下:
name:realFieldName
看输出结果我们是成功获取了TestAnnotation类中mField成员变量和testAnimationMethod方法的注解元信息,代码注释很详细,就不解释了。