kotlin - 将注释传递给 Kotlin 中的函数

标签 kotlin cdi

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

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

像这样调用构造函数 cdiInstance.select(MyClass::javaClass, MyAnnotation()) 是不允许的,并且 @Annotation-Syntax cdiInstance.select(MyClass::javaClass, @MyAnnotation)也不允许作为参数。我怎样才能存档这个?

最佳答案

使用 CDI 时,您通常还会有 AnnotationLiteral可用,或者至少您可以相当简单地实现类似的东西。

如果您想使用注释选择一个类,则可以使用以下方法:

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

或者,如果您需要特定值,您可能需要实现特定的 AnnotationLiteral 类。在 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 或者我只是没有看到如何实现(另请参阅相关问题: Implement (/inherit/~extend) annotation in Kotlin )。

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

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

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

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

关于kotlin - 将注释传递给 Kotlin 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590623/

相关文章:

java - Kotlin Spring Boot 测试端点和服务层,并模拟存储库层

Java MessageFormat 无法格式化

javax.enterprise.event.Event : How to initialize the pushEvent

java - CDI:为什么我的 transient 字段被序列化?

java - 使用@RequestScoped CDI bean的@Remote EJB

android - 启动 Activity 时无法识别 Android Studio 中的类 Intent

android - 如何在 Android 30 中打开位置权限设置?

jsf - 是什么使 Bean 成为 CDI Bean?

gradle - 调试库

jakarta-ee - 程序化对话查找