在Java中,我可以"实现"注释.
示例Java注释:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaClassAnno {
String[] value();
}
Java"实现"示例:
class MyAnnotationLiteral
extends AnnotationLiteral<JavaClassAnno>
implements JavaClassAnno { // <--- works in Java
private String value;
public MyAnnotationLiteral(String value) {
this.value = value;
}
@Override
public String[] value() {
return new String[] { value };
}
}
Trying to port that to Kotlin doesn't work as it says that the annotation is final and therefore can not be inherited, i.e. the following will not work:
class MyAnnotationLiteral(private val internalValue: String)
: AnnotationLiteral<JavaClassAnno>(),
JavaClassAnno { // <--- doesn't work in Kotlin (annotation can not be inherited)
override fun value(): Array<String> {
return arrayOf(internalValue)
}
}
如何以Kotlin方式"实现/扩展"注释?找不到Kotlin在这方面与Java不同的任何原因.欢迎任何关于如何解决这个问题的提示,或者任何告诉我们为什么会这样做的消息来源.
下面的问题包含了这个星座的一个用例:Dynamically fire CDI event with qualifier with members.
Note that this would also apply to a Kotlin annotation as well as it seems that a Kotlin annotation can not be open and therefore not be implemented/extended too.
到目前为止,我发现@Inherited
是个问题:
- https://discuss.kotlinlang.org/t/inherited-annotations-and-other-reflections-enchancements/6209
- https://youtrack.jetbrains.com/issue/KT-22265
但我没有找到任何理由说明注释不能像Java中那样实现/继承.
I also asked this question now here: https://discuss.kotlinlang.org/t/implement-inherit-extend-annotation-in-kotlin/8916
Update: Finally I found something regarding this design decision, namely the following issue (while I was opening my own issue for it): Annotations inheritance. Either prohibit or implement correctly. As it seems the decision was to "prohibit" it, even though there are no (visible?) comments, discussions or other sources about that decision.