将注释传递给Kotlin中的函数
如何将注释实例传递给函数 我想调用java方法将注释传递给Kotlin中的函数,kotlin,cdi,Kotlin,Cdi,如何将注释实例传递给函数 我想调用java方法AbstractCDI.select(类类型、注释…限定符)。但是我不知道如何将注释实例传递给这个方法 像这样调用构造函数 cdiInstance.select(MyClass::javaClass,MyAnnotation()) 不允许,@Annotation SyntaxcdiInstance.select(MyClass::javaClass,@MyAnnotation)也不允许作为参数。如何存档此文件?可以使用注释对方法或字段进行注释,并在每
AbstractCDI.select(类类型、注释…限定符)
。但是我不知道如何将注释实例传递给这个方法
像这样调用构造函数
cdiInstance.select(MyClass::javaClass,MyAnnotation())
不允许,@Annotation Syntax
cdiInstance.select(MyClass::javaClass,@MyAnnotation)
也不允许作为参数。如何存档此文件?可以使用注释对方法或字段进行注释,并在每次反射时获取:
this.javaClass.getMethod(“annotatedMethod”).getAnnotation(MyAnnotation::class.java)
或者根据罗兰的建议,采用上述kotlin版本:
MyClass::annotatedMethod.findAnnotation()代码>
正如罗兰为CDI提出的建议,最好使用AnnotationLiteral
(参见他的文章)。当使用CDI
时,通常也有可用的工具,或者至少可以很容易地实现类似的工具
如果要使用注释选择类,请执行以下操作:
cdiInstance.select(MyClass::class.java, object : AnnotationLiteral<MyAnnotation>() {})
然而,在Kotlin中,您无法实现注释和扩展AnnotationLiteral
,或者我只是不知道如何实现(另请参见相关问题:)
如果您希望继续使用反射来访问注释,那么您可能应该改用Kotlin反射方式:
ClassWithAnno::class.annotations
ClassWithAnno::methodWithAnno.annotations
调用filter
等以获取所需的注释,或者如果您知道那里只有一个注释
,也可以调用以下(findAnnotation
是KAnnotatedElement
上的扩展函数):
ClassWithAnno::class.findAnnotation()
ClassWithAnno::methodWithAnno.FindAnotation()
谢谢!AnnotationLiteral正是我要找的!不客气!请注意,我还添加了一个关于AnnotationLiteral
实现的问题,用于需要指定自定义值的情况(例如,缩小应该使用哪个限定符)。如果您不要求自己是幸运的,AnnotationLiteral
将按原样工作。如果您这样做了,那么您现在可能需要使用Java实现作为解决方案,因为Kotlin似乎不支持它。
ClassWithAnno::class.annotations
ClassWithAnno::methodWithAnno.annotations
ClassWithAnno::class.findAnnotation<MyAnnotation>()
ClassWithAnno::methodWithAnno.findAnnotation<MyAnnotation>()