版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jing85432373/article/details/78480621
参考文章: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;
}