Java 如何从拦截器访问注释变量
假设我有一个简单的注释Java 如何从拦截器访问注释变量,java,annotations,interceptor,Java,Annotations,Interceptor,假设我有一个简单的注释 @InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface CheckUserRole { @Nonbinding String[] allowedRoles() default ""; } 接下来,我将拦截器定义如下: @Interceptor @CheckUserRole public class CheckUserRoleInterceptor 如何
@InterceptorBinding
@Retention(RUNTIME) @Target({TYPE, METHOD})
public @interface CheckUserRole {
@Nonbinding String[] allowedRoles() default "";
}
接下来,我将拦截器定义如下:
@Interceptor
@CheckUserRole
public class CheckUserRoleInterceptor
如何从批注访问允许的角色
?我是这样做的:
CheckUserRole checkUserRoleAnnotation = ctx.getMethod().getAnnotation(CheckUserRole.class);
if(checkUserRoleAnnotation != null){
String[] allowedRoles = checkUserRoleAnnotation.allowedRoles();
}
但这只有在类中对方法使用注释时才有效。如果我想在整个类上使用注释,checkUserRoleAnotation
是null
,因为我的方法在代码中没有注释
当对整个类进行注释时,如何访问这些变量?我找到了解决这个问题的好方法。要从方法或类访问注释(如果方法级别上没有注释),请使用my函数:
// Returns annotation from method or class (if does not exist, returns null)
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object getAnnotationClass(Class clazz, InvocationContext ctx){
Object annotationClass = ctx.getMethod().getAnnotation(clazz);
// Try to find annotation on class level
if(annotationClass == null){
annotationClass = ctx.getTarget().getClass().getSuperclass().getAnnotation(clazz);
}
return annotationClass;
}
我的职能是:
.getSuperclass()
,因为.getClass()
返回代理
用法示例:
CheckUserRole annotationClass = (CheckUserRole) getAnnotationClass(CheckUserRole.class, ctx);
if(annotationClass != null){
String[] allowedRoles = annotationClass.allowedRoles();
}
使用:
@上下文
资源信息资源信息
使用ResourceInfo对象,您将能够获得相关的类和方法(以及其他有用的信息)
使用之后
Annotationabc=resourceInfo.getResourceMethod().getAnnotation(Annotationabc.class)
要在ur方法上获取注释可以在处理注释的类中访问它,而不是在放置注释本身的类中访问它@Constraint(validatedBy=Validator.class)->在Validator.java文件中,您可以访问注释的成员,我的意思是我想在拦截器中访问它。也许我没有解释清楚。我在这个类中有class
ExampleClass
和void exampleMethod()
。当我注释exampleMethod()
时,我可以访问拦截器中的变量(如上所述),但当我用它注释ExampleClass
时,所有方法都应该注释,但它返回null
。是的,我得到了。那么,是什么阻止您将@Constraint(validatedBy=CheckUserRoleInterceptor.class)添加到注释中?请您解释一下?当我将@约束(validatedBy=CheckUserRoleInterceptor.class)
添加到public@interface CheckUserRole
时,需要扩展约束验证器。我从来没有使用过验证器,所以我真的不知道如何从那个里访问变量。可能还有其他方法,但若不是为了验证,你们到底想要它做什么?