繁体   English   中英

使用自定义注释的调用方法-JAVA

[英]Invoke Method Using Custom Annotation - JAVA

我在dropwizard中构建一个通用的异常处理程序。 我想提供自定义注释作为库的一部分,每当方法(包含注释的方法)中引发异常时,该方法都会调用handleException方法。

详细信息:自定义注释为@ExceptionHandler

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExceptionHandler{
    Class<? extends Throwable>[] exception() default {};
}

ExceptionHandlerImpl有一个处理程序方法handleException(Exception, Request)

现在有一个带有注释方法的业务类

@ExceptionHandler(exception = {EXC1,EXC2})
Response doPerformOperation(Request) throws EXC1,EXC2,EXC3{}

现在,每当通过doPerformOperation方法引发EXC1EXC2 ,我都想调用handleException方法。

我尝试阅读有关AOP(AspectJ),反射的内容,但无法找出执行此操作的最佳方法。

我已经使用Aspectj解决了这个问题。 我已经创建了界面

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HandleExceptionSet {
    HandleException[] exceptionSet();
}

其中HandleException是另一个注释。 这是为了允许异常数组。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface HandleException {
    Class<? extends CustomException> exception() default CustomException.class;
}

现在,我有一个具有处理程序的ExceptionHandler类。 要将方法绑定到此批注,我在模块中使用以下配置。

bindInterceptor(Matchers.any(), Matchers.annotatedWith(HandleExceptionSet.class), new ExceptionHandler());

我在带有以下代码段的类中使用此批注。

@HandleExceptionSet(exceptionSet = {
        @HandleException(exception = ArithmeticException.class),
        @HandleException(exception = NullPointerException.class),
        @HandleException(exception = EntityNotFoundException.class)
})
public void method()throws Throwable {
    throw new EntityNotFoundException("EVENT1", "ERR1", "Entity Not Found", "Right", "Wrong");
}

现在这对我有用。 不知道这是否是最好的方法。

有没有更好的方法来实现这一目标?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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