【问题标题】:Pass annotation to a function in Kotlin将注释传递给 Kotlin 中的函数
【发布时间】:2018-07-30 09:15:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: kotlin cdi


    【解决方案1】:

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

    如果你想使用你的注释选择一个类,下面应该可以解决问题:

    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,或者我只是没有看到如何实现(另请参阅相关问题: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>()
    

    【讨论】:

    • 谢谢! AnnotationLiteral 正是我搜索的内容!
    • 不客气!请注意,我还添加了一个关于AnnotationLiteral 实施的问题,用于您需要指定自定义值的情况(例如,缩小应采用的限定符)。如果您不要求您很幸运,AnnotationLiteral 将照常工作。如果你这样做了,那么你现在可能需要使用 Java 实现作为解决方法,因为 Kotlin 似乎不支持它。
    【解决方案2】:

    可以用注解对方法或字段进行注解,然后根据反射获取它:

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

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

    MyClass::annotatedMethod.findAnnotation&lt;MyAnnotation&gt;()!!

    根据 Roland 对 CDI 的建议,最好使用 AnnotationLiteral(参见他的帖子)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多