簡體   English   中英

如何將注釋類型作為方法參數傳遞?

[英]How to pass Annotation Type as a method parameter?

有一種處理注釋的方法,例如

public void getAnnotationValue(ProceedingJoinPoint joinPoint)
{
     MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
     Method method = methodSignature.getMethod();
     Annotation annotation = method.getParameterAnnotations()[0][0];
    RequestHeader requestParam = (RequestHeader) annotation;
    System.out.println(requestParam.value());
}

我想將其轉換為接受joinPoint和Annotation Type之類的通用方法

getAnnotationValue(joinPoint, RequestHeader);

為此,我嘗試使用:

public void getAnnotationValue(ProceedingJoinPoint joinPoint, Class<? extends Annotation> annotationType)
    {
         MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
         Method method = methodSignature.getMethod();
         Annotation annotation = method.getParameterAnnotations()[0][0];
        annotationType requestParam = (annotationType) annotation;
        System.out.println(requestParam.value());
    }

但這會提示錯誤,指出type unresolved error 如何處理並將注釋值傳遞給該函數!

您可以執行的“最佳”操作:

public void foo(Class<? extends java.lang.annotation.Annotation> annotationClass) { ...

注釋沒有特定的“類型”類,但是您可以使用普通的Class對象,只是表示您希望Annotation基類為子類。

您想要做的只是無法正常工作。 問題不在於方法簽名,而是您對如何在Java中使用類型的錯誤理解。 在這條線...

annotationType requestParam = (annotationType) annotation;

...您有兩個錯誤:

  • 您不能使用annotationType requestParam聲明變量,因為annotationType類型不是類名文字而是變量名。 這是語法錯誤,編譯器將其標記為錯誤。
  • 出於與第一種情況相同的原因,您不能使用(annotationType) annotation進行投射。 Java不能那樣工作,代碼只是無效的。

話雖如此,稍后在您的代碼上假設捕獲的注釋類具有方法value() ,這對於某些注釋類可能恰好是正確的,但在一般情況下不起作用。 但是,假設在調用輔助方法的所有情況下確實存在該方法,則可以將其更改為如下所示:

public void getAnnotationValue(JoinPoint joinPoint) {
  MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
  Method method = methodSignature.getMethod();
  Annotation annotation = method.getParameterAnnotations()[0][0];
  Class<? extends Annotation> annotationType = annotation.annotationType();
  try {
    System.out.println(annotationType.getMethod("value").invoke(annotation));
  } catch (Exception e) {
    throw new SoftException(e);
  }
}

IMO這很丑陋,也不是很好的編程方法。 但是它可以編譯並運行。 順便說一句,如果注釋類型沒有value()方法,您將看到NoSuchMethodException

我認為您在這里遇到XY問題 您不是在描述要解決的實際問題,而是描述解決方案的樣子,使自己和其他人不知所措,以尋求解決問題的更好方法。 因此,我的示例代碼可能並不能真正解決您的問題,而只是使您的難看解決方案以某種方式起作用。 這與好的設計不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM