如何处理拦截器绑定中的属性

时间:2012-05-05 21:53:45

标签: java java-ee-6 interceptor

我有一个注释:

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Example {
}

它的处理拦截器类:

@Interceptor
@Example
public class ExampleInterceptor implements Serializable {
...
}

我想添加一个参数文本:

public @interface Example {
    String text();
}

但我不知道如何处理拦截器类中的参数。如何修改类的注释?

@Interceptor
@Example(text=???????)
public class ExampleInterceptor implements Serializable {
...
}

如果我写@Example(text="my text"),则在使用@Example(text="my text")注释方法/类时调用拦截器。但我希望拦截器能够在参数值上独立调用 - @Example(text="other text")

如何获取参数值?我是否必须使用反思或有更好的方法吗?

2 个答案:

答案 0 :(得分:13)

使用注释@Nonbinding时,会为每个属性值调用拦截器。

注释:

public @interface Example {
    @Nonbinding String text() default "";
}

拦截器:

@Interceptor
@Example
public class ExampleInterceptor implements Serializable {
    ...
}

答案 1 :(得分:0)

首先,如果您只有一个参数,则可以将其命名为value,然后可以跳过参数名称(默认值),=>可以跳过text = part,例如:

@Example("my text") //instead of @Example(test="My text")
public class ...

要访问注释,请使用您必须获得的getAnnotationClassMethodField类型的方法Constructor。然后,您将获得一个可以调用方法的注释实例。

Example example = getClass().getAnnotation(); //if you are inside the interceptor you can just use getClass(), but you have to get the class from somewhere
example.value(); //or example.text() if you want your annotation parameter to be named text.
相关问题