将注释传递给 Kotlin 中的函数

Pass annotation to a function in Kotlin

如何将注释实例传递给函数?

我想调用 java 方法 AbstractCDI.select(Class<T> type, Annotation... qualifiers)。但我不知道如何将注释实例传递给此方法。

像这样调用构造函数 cdiInstance.select(MyClass::javaClass, MyAnnotation()) 不允许,@Annotation-Syntax cdiInstance.select(MyClass::javaClass, @MyAnnotation) 也不允许作为参数。我该如何存档?

可以使用注释对方法或字段进行注释,并通过反射获取它:

this.javaClass.getMethod("annotatedMethod").getAnnotation(MyAnnotation::class.java)

或者根据Roland的建议,上面的kotlin版本:

MyClass::annotatedMethod.findAnnotation<MyAnnotation>()!!

正如 Roland 对 CDI 的建议,最好使用 AnnotationLiteral(参见他的 post)。

在使用 CDI 时,您通常也可以使用 AnnotationLiteral,或者至少您可以相当容易地实现类似的东西。

如果你想 select 一个 class 使用你的注释下面应该做的伎俩:

cdiInstance.select(MyClass::class.java, object : AnnotationLiteral<MyAnnotation>() {})

或者如果您需要特定的值,您可能需要实施特定的 AnnotationLiteral-class。在 Java 中,其工作方式如下:

class MyAnnotationLiteral extends AnnotationLiteral<MyAnnotation> implements MyAnnotation {
    private String value;

    public MyAnnotationLiteral(String value) {
        this.value = value;
    }
    @Override
    public String[] value() {
        return new String[] { value };
    }
 }

然而,在 Kotlin 中,您无法实现注释并扩展 AnnotationLiteral 或者我可能只是没有看到如何(另请参阅相关问题:)。

如果您想继续使用反射来访问注释,那么您可能应该改用 Kotlin 反射方式:

ClassWithAnno::class.annotations
ClassWithAnno::methodWithAnno.annotations

调用filter等来得到你想要的Annotation,或者如果你知道那里只有一个Annotation,你也可以只调用下面的(findAnnotationKAnnotatedElement 上的扩展函数):

ClassWithAnno::class.findAnnotation<MyAnnotation>()
ClassWithAnno::methodWithAnno.findAnnotation<MyAnnotation>()