如何在 Kotlin 中表达数组注释参数?

diz*_*iaq 3 annotations spring-annotations kotlin

当注释具有基本类型(如 String 或 Int)的数组参数时,如何使用它很简单:

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

@MyAnnotation(props = ["A", "B", "C"])
class Foo {}
Run Code Online (Sandbox Code Playgroud)

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

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

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

public @interface PropertySource { 
  String[] value();
}
Run Code Online (Sandbox Code Playgroud)

在Java中语法用法是

@PropertySources({
    @PropertySource({"A", "B", "C"}),
    @PropertySource({"D", "E", "F"}),
})
class Foo{}
Run Code Online (Sandbox Code Playgroud)

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

@PropertySources([
    @PropertySource(["A", "B", "C"]),
    @PropertySource(["D", "E", "F"]),
])
class Foo{}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*Tom 5

在子注释声明中添加value =和删除:@

@PropertySources(value = [
  PropertySource("a", "b"),
  PropertySource("d", "e"),
])
class Foo
Run Code Online (Sandbox Code Playgroud)

另请注意,@PropertySource这样@Repeatable您就可以执行以下操作:

@PropertySource("a", "b")
@PropertySource("d", "e")
class Foo
Run Code Online (Sandbox Code Playgroud)