在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是个问题:

但我没有找到任何理由说明注释不能像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.

添加了以下问题:https://youtrack.jetbrains.com/issue/KT-25947

推荐答案

从Kotlin 1.3开始,不支持这种情况.要创建注释的自定义实例,现在必须求助于Java.做出这种设计决策的原因之一是,制作注释接口过于特定于JVM,无法很好地映射到其他平台.

Kotlin相关问答推荐

API迁移到Spring Boot 3后,Spring Security无法工作

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

Microronaut Data 4和JDbi

在 Kotlin 中将两个字节转换为 UIn16

kotlin 模式匹配如何像 scala 一样工作

如何在 Kotlin 中将with代码转换为完整代码?

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

奇怪的 cotlin check Not Null 参数错误

Kotlin 协程中的 Dispatchers.Main 和 Dispatchers.Default 有什么区别?

Map.mapTo 到另一个map

Kotlin的web-framework框架

在kotlin中,如何模拟封装回调函数?

Kotlin解构when/if语句

Kotlin Native如何将字节数组转换为字符串?

这是 Kotlin 中的错误还是我遗漏了什么?

使用 kotlin 每 3 位数添加逗号或点

Kotlin:在何时使用枚举

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?

Dagger 2 androidx fragment不兼容类型