简体   繁体   中英

CDI interceptor for a specific type

@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresPageReload {
}

public interface Page{
    public static final String LOAD_STR = "load";
    public void load();
}
@RequestScoped
public class PageImpl1 implements Page{
    public void load(){
        //...
    }

    @RequiresPageReload
    public String foo(){
        //...
        return "foo1";
    }
}
@RequestScoped
public class MyObject{
    @RequiresPageReload
    public String foo2(){
        //...
        return "foo2";
    }
}

@RequiresPageReload
@Interceptor
public class RequiresPageReloadInterceptor implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @AroundInvoke
    public Object forceReload(InvocationContext context) throws Exception {
        Object result = context.proceed();
        context.getMethod().getDeclaringClass().getDeclaredMethod(Page.LOAD_STR).invoke(context.getTarget()); //***
        return result;
    }

}

In the line marked with stars, of course I can check through reflection if the method exists and decide accordingly what to do. But I wonder whether is there a better way to achieve the same behavior? For example, is it possible to associate interceptors to just a specific type (in this example, imagine I don't want the foo2() method of MyObject to be intercepted because such object does not implement Page)? I considered also using Decorators, but there the problem is "foo"s method don't belong to an interface..

thank you!

听起来您想要的是一个装饰器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM