您的位置:首页 > 其它

重复注解与获取方法返回值泛型类型

2017-09-09 00:00 204 查看
Repeatable元注解,标记了此注解的注解。

能够在注解声明的地方多次使用。

此注解需要新增一个其它注解来配合使用。例如我有一个验证注解:

Repeatable.值为ValidateMapping。ValidateMapping中包含Validate注解的返回值 声明。

/**
*
* 验证标记接口,标记这个动作要做走哪些验证方法
* @author caomin
* @version 1.0
* @Date 2017-09-04 13:47
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ValidateMapping.class)
public @interface Validate {
/**
* 执行动作
* @return
*/
Action value();

/**
* 执行顺序,从1开始
* @return
*/
int order();
}


声明一个注解ValidateMapping,其返回值为要重复使用的那个注解的数组类型。

/**
*重复注解
* Created by caomin on 2017/9/8.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateMapping {
Validate[] value() default {};
}


在获取值时,需要这样获取:

Validate annotation = method.getAnnotation(Validate.class);
ValidateMapping validateMapping = method.getAnnotation(ValidateMapping.class);
if (annotation!=null){
if (action==annotation.value()){
methodList[annotation.order()]=method;
}
}else if (validateMapping!=null){//重复注解
for (Validate validate : validateMapping.value()) {
if (action==validate.value()){
methodList[validate.order()]=method;
}
}
}

如果一个方法只打了一个此种类型的注解,那么直接获取即可。如果打了多个此种类型的注解。需要获取声明的那个注解类型。然后通过其中的方法,获取实际的值。

获取某个方法,返回值的泛型的具体类型:

需要注意,必须获取对象的class对象,而不是代理对象。如果是代理对象,则获取不到他的真实对象

private String getReturnName(Class clazz,Method method) throws IllegalAccessException, InstantiationException, NoSuchMethodException {
Class<?>[] parameterTypes = method.getParameterTypes();
Method declaredMethod = clazz.getMethod(method.getName(), parameterTypes);
Type genericReturnType = declaredMethod.getGenericReturnType();
Class<?> returnType = declaredMethod.getReturnType();
 if (genericReturnType instanceof ParameterizedType) {//如果包含泛型 ParameterizedType parameterizedType = (ParameterizedType) genericReturnType; //获取真实类型 Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); String returnName = returnType.getSimpleName();
//泛型名字
String fanName = "";
if (returnType.newInstance() instanceof Map) {
if (actualTypeArguments.length == 2) {
fanName = ((Class) actualTypeArguments[1]).getSimpleName().toLowerCase();
}
} else if (returnType.newInstance() instanceof Collection) {
if (actualTypeArguments.length != 0) {
fanName = ((Class) actualTypeArguments[0]).getSimpleName().toLowerCase();
}
}
return fanName + returnName;
} else {//不是泛型
return returnType.getSimpleName().toLowerCase();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息