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

Invoke Method Using Custom Annotation - JAVA

我正在 dropwizard 中构建通用异常处理程序。我想提供自定义注释作为库的一部分,只要在方法(包含注释的方法)中引发异常,它就会调用 handleException 方法

详情: 自定义注释为 @ExceptionHandler

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

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

现在有一个企业class有带注解的方法

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

现在每当 EXC1EXC2 被方法 doPerformOperation 引发时,我想调用 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 class,它有处理程序。要将方法绑定到此注释,我在模块中使用以下配置。

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

我在 classes 中使用了这个注解,代码如下。

@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");
}

这对我有用。 不确定,这是否是最好的方法。

有没有更好的方法来实现这个?