带有可选参数的 Kotlin 注解

Kotlin annotation with optional parameters

自定义注解定义如下:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)    
annotation class Custom(val a: String, 
        val b: String = "[null]", 
        val c: String = "[null]")

所需用法:

1.

@Custom(a = "Testa", b = "Testb", c = "Testc")
fun xyz(){ ... }

2.

@Custom(a = "Testa")
fun pqr(){ ... }

当我尝试所需的用法 #2 时,它抛出 No values passed for parameter "b"

如何实现kotlin cusotm注解中有可选参数?

您的代码按原样工作,可以通过

验证
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)    
annotation class Custom(val a: String, 
        val b: String = "[null]", 
        val c: String = "[null]")

object W {
    @Custom(a = "Testa")
    fun pqr(){}
}

fun main(args: Array<String>) {
    println(W::class.java.getMethod("pqr").getAnnotations()[0])
}

打印 @Custom(b=[null], c=[null], a=Testa),因此 bc 得到了它们的默认值。 (您也可以写 W::pqr.annotations[0],但这在操场上不起作用。)