如何将Annotation Type作为方法参数传递?

问题描述 投票:1回答:2

有一种方法可以处理类似的注释

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?如何处理它并将注释值传递给该函数!!

java annotations spring-aop aspect
2个回答
0
投票

你可以做的“最好”的事情:

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

Annotations没有特定的“类型”类,但是您可以回退到普通的Class对象,并简单地表达您期望Annotation基类的子类。


0
投票

你想做的只是不这样做。问题不是方法签名,而是您对如何在Java中使用类型的错误理解。在这一行......

annotationType requestParam = (annotationType) annotation;

......你有两个错误:

  • 您不能使用annotationType requestParam声明变量,因为annotationType不是类名文字而是变量名。这是语法错误,编译器会将其标记为。
  • 您不能使用(annotationType) annotation进行投射,原因与第一种情况相同。 Java不会那样工作,代码只是无效。

话虽如此,稍后您的代码假定捕获的注释类有一个方法value(),对于某些注释类可能恰好是真的,但在一般情况下不起作用。但是假设在调用helper方法的所有情况下都存在该方法,您可以将其更改为以下内容:

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

国际海事组织这是非常丑陋和不好的编程。但它编译并运行。顺便说一句,如果注释类型没有value()方法,你会看到抛出的NoSuchMethodException

我想你在这里受到XY problem的影响。您没有描述您想要解决的实际问题,而是您认为解决方案应该是这样的方式,让自己和其他人感到茫然,以便更好地解决问题。因此,我的示例代码可能并没有真正解决您的问题,只是让您的丑陋解决方案以某种方式工作。这与优秀设计不同。

© www.soinside.com 2019 - 2024. All rights reserved.