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

标签 java annotations aop aspectj dropwizard

我正在 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)、Reflection 的内容,但无法找出执行此操作的最佳方法。

最佳答案

我已经使用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 类,它有处理程序。要将方法绑定(bind)到此注释,我在模块中使用以下配置。

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

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

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

关于java - 使用自定义注释调用方法 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523429/

相关文章:

.net - 现有 .NET Web 应用程序中的被动日志记录?

java - Spring AOP 建议被执行两次

java - 如何在JSP页面中垂直打印出ArrayList对象?

java - 如何使用AOP拦截File、FileReader、FileWriter、FileInputStream、FileOutputStream的构造函数?

java - 私有(private)方法可以在java类外访问

java - 编译器说注释的 "value must be a constant"

emacs - 图阿雷格模式和caml模式

PHP 注释框架

java - Java (JIT) 可以内联递归方法吗?

java - 如何在java中删除String数组中的所有元素?