您的位置:首页 > 移动开发 > Android开发

android 自定义注解 通过反射获取注解属性值

2017-11-08 16:52 357 查看
参考文章:http://xuwenjin666.iteye.com/blog/1637247

1.自定义注解

package cn.veji.hibernate.po;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Privilege {
String[] value();

}


public enum ElementType {
TYPE,// 类、接口、注解类型或枚举
FIELD, //属性
METHOD, //方法
PARAMETER,// 用于描述参数
CONSTRUCTOR,//构造方法
LOCAL_VARIABLE,//局部变量
ANNOTATION_TYPE,//注解类
PACKAGE //包
}


从上面代码可以看出Target 对应的作用域(Target可以接受多个参数,逗号分隔即可)

例如:

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTestIn {
String author() default "kaelthas.wang";
String address() default "山东青岛";

}


2.获取类注解属性值

/**
* 读取注解值
*
* @param annotationClasss 处理Annotation类名称
* @param annotationField 处理Annotation类属性名称
* @param className 处理Annotation的使用类名称
* @return
* @throws Exception
*/
@SuppressWarnings("all")
public Map<String, String> loadVlaue(Class annotationClasss,
String annotationField, String className) throws Exception {

System.out.println("处理Annotation类名称  === "+annotationClasss.getName());
System.out.println("处理Annotation类属性名称  === "+annotationField);
System.out.println("处理Annotation的调用类名称  === "+className);
Map<String, String> map = new HashMap<String, String>();
Method[] methods = Class.forName(className).getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(annotationClasss)) {
Annotation p = method.getAnnotation(annotationClasss);
Method m = p.getClass()
.getDeclaredMethod(annotationField, null);
//这里根据属性参数类型进行强制类型转换
String[] values = (String[]) m.invoke(p, null);
for (String key : values) {
System.out.println("注解值 === " + key);
map.put(key, key);
}
}
}
System.out.println("map数量  === " + map.size());
return map;
}


3.获取方法注解属性值

这里的属性值为int 强制类型转换时候使用Integer

@SuppressWarnings("all")
public int loadVlaue(Class annotationClasss,
String annotationField, String className) {

System.out.println("处理Annotation类名称  === " + annotationClasss.getName());
System.out.println("处理Annotation类属性名称  === " + annotationField);
System.out.println("处理Annotation的调用类名称  === " + className);
Map<String, String> map = new HashMap<String, String>();

try {
Method[] methods = Class.forName(className).getDeclaredMethods();

Class test = Class.forName(className);
if (test.isAnnotationPresent(annotationClasss)) {
Annotation p = test.getAnnotation(annotationClasss);
Method m = p.getClass()
.getDeclaredMethod(annotationField, null);
return (Integer) m.invoke(p, null);

}
} catch (Exception e) {
return -1;
}

return -1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息