簡體   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