【问题标题】:How to express array annotation argument in Kotlin?如何在 Kotlin 中表达数组注释参数?
【发布时间】:2021-12-30 12:43:35
【问题描述】:

当注解有一个基本类型如 String 或 Int 的数组参数时,如何使用它很简单:

public @interface MyAnnotation{
  String[] props();
}

@MyAnnotation(props = ["A", "B", "C"])
class Foo {}

不幸的是,这不适用于本身就是注释的值。

一个例子是org.springframework.context.annotation.PropertySources:

public @interface PropertySources {
  PropertySource[] value();
}

public @interface PropertySource { 
  String[] value();
}

在Java中的语法用法是

@PropertySources({
    @PropertySource({"A", "B", "C"}),
    @PropertySource({"D", "E", "F"}),
})
class Foo{}

但在 Kotlin 中,类似方法的代码无法编译

@PropertySources([
    @PropertySource(["A", "B", "C"]),
    @PropertySource(["D", "E", "F"]),
])
class Foo{}

在 Kotlin 中如何表达这种注解数组嵌套构造?

【问题讨论】:

    标签: kotlin annotations spring-annotations


    【解决方案1】:

    在子注解声明中添加value = 并删除@

    @PropertySources(value = [
      PropertySource("a", "b"),
      PropertySource("d", "e"),
    ])
    class Foo
    

    还要注意 @PropertySource@Repeatable 所以你可以这样做:

    @PropertySource("a", "b")
    @PropertySource("d", "e")
    class Foo
    

    【讨论】:

    • 诀窍在于“值=”。好的,不错。你确定第二个代码块编译了吗?
    • 是的,注意我用的是最新的 kotlin (1.6.10)
    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多