首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JEE6:在拦截器实现中获取绑定注释

JEE6:在拦截器实现中获取绑定注释
EN

Stack Overflow用户
提问于 2012-01-25 01:09:31
回答 2查看 2.6K关注 0票数 1

我有一个拦截器绑定,它是参数化的:

代码语言:javascript
运行
复制
@InterceptorBinding
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Traced {

   @Nonbinding
   boolean traceFull() default true;
}

然后,我定义了一个拦截器实现

代码语言:javascript
运行
复制
@Interceptor
@Traced
public class TracingInterceptor implements Serializable { ... }

在实现中,我希望检查traceFull-参数设置了哪个值。(我不想为true、false和null实现三个拦截器)

所以我的实现检查被拦截方法的Interceptor-Binding-Annotation:

代码语言:javascript
运行
复制
Traced traceAnnotation = context.getMethod().getAnnotation(Traced.class);
if (traceAnnotation != null && traceAnnotation.traceFull()) { ... }

这可以很好地工作,但是如果我使用一个构造型或者一个嵌套的拦截器绑定,那么我不会得到这个方法的@Traced注解,我也不能检查设置的值。

所以我的问题是:如何在我的拦截器实现中获得“调用”绑定?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-26 03:58:42

这在CDI 1.0中是不可能的,但在CDI 1.1中应该是可能的

票数 0
EN

Stack Overflow用户

发布于 2014-07-03 19:09:16

您甚至可以使用反射来解析构造型中的注释。

在同样的情况下(在拦截器中需要额外的非绑定信息),我实现了一个实用方法:

代码语言:javascript
运行
复制
public <T extends Annotation> T findBindingAnnotation( Class<T> bindingType, InvocationContext ic )
{
    Method method = ic.getMethod();
    if ( method != null && method.isAnnotationPresent( bindingType ) )
    {
        return method.getAnnotation( bindingType );
    }
    Class<? extends Object> type = ic.getTarget().getClass();
    if ( type.isAnnotationPresent( bindingType ) )
    {
        return type.getAnnotation( bindingType );
    }

    T annotationFromStereoType = annotationFromStereoType( bindingType, type );
    if ( annotationFromStereoType != null )
    {
        return annotationFromStereoType;
    }

    throw new UnsupportedOperationException( "no binding annotation found: " + bindingType.getCanonicalName() );
}

private <T extends Annotation> T annotationFromStereoType( Class<T> bindingType, Class<? extends Object> type )
{
    for ( Annotation annotation : type.getAnnotations() )
    {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if ( annotationType.isAnnotationPresent( Stereotype.class ) )
        {
            if ( annotationType.isAnnotationPresent( bindingType ) )
            {
                return annotationType.getAnnotation( bindingType );
            }
            else
            {
                T recursiveLookup = annotationFromStereoType( bindingType, annotationType );
                if ( null != recursiveLookup )
                {
                    return recursiveLookup;
                }
            }
        }
    }
    return null;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8990998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档