带有可选参数的Kotlin注释

带有可选参数的Kotlin注释,kotlin,annotations,Kotlin,Annotations,自定义注释定义如下: @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class Custom(val a: String, val b: String = "[null]", val c: String = "[null]") 预期用途: 一, 二, 当我尝试所需的用法#2时,它不会为参数“b”抛出任何值 如何在kotlin

自定义注释定义如下:

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

一,

二,

当我尝试所需的用法#2时,它不会为参数“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])
}
@Target(AnnotationTarget.FUNCTION)
@保留(AnnotationRetention.RUNTIME)
注释类自定义(val a:字符串,
val b:String=“[null]”,
val c:String=“[null]”)
对象W{
@自定义(a=“Testa”)
fun pqr(){}
}
趣味主线(args:Array){
println(W::class.java.getMethod(“pqr”).getAnnotations()[0])
}

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

您的代码似乎在运行良好。太奇怪了。我的intellij IDE显示错误并执行渐变构建,但它失败了。甚至还检查了kotlin版本:1.3.21。这超出了我的理解范围。我想报告错误吧@对不起。撕破我自己。这么大的错误。我正在为默认值配置另一个参数,并且正在删除我认为设置为可选的必需参数。我注意到这是我一生中最愚蠢、最愚蠢的事情之一。非常感谢您的时间和帮助。@AlexeyRomanov您能否提交链接中共享的代码片段作为答案。我会接受的。这也将帮助其他人快速繁殖。
@Custom(a = "Testa")
fun pqr(){ ... }
@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])
}