如何将注释实例传递给函数?
我想调用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
,你也可以直接调用以下代码(findAnnotation
是 KAnnotatedElement
上的扩展函数):
ClassWithAnno::class.findAnnotation<MyAnnotation>()
ClassWithAnno::methodWithAnno.findAnnotation<MyAnnotation>()
关于kotlin - 将注释传递给 Kotlin 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590623/