【问题标题】:How to apply annotation to getter of delegated property in Kotlin?如何在 Kotlin 中将注释应用于委托属性的 getter?
【发布时间】:2019-05-08 07:44:42
【问题描述】:

在使用 Kotlin 时,我想添加包定义的常量作为序列化类属性的前缀。杰克逊是兄弟,所以我写了这个:

var prop: String = ""
    @JsonGetter(value = "prop")
    get() = PREFIX + field

它工作得很好,所以为了简洁起见,我决定用委托属性替换它:

@get:JsonGetter(value = "prop") var prop: String by PrefixedProperty()

...

class PrefixedProperty(var field: String = "") {
    operator fun getValue(blah blah) = PREFIX + field
    ...
}

然后 BOOM——我的财产消失了。

看来,prop 的委托 getter 没有应用注释。是否有可能实现所需的行为?

【问题讨论】:

    标签: kotlin jackson annotations jvm


    【解决方案1】:

    你应该这样注释它:

    @delegate:JsonGetter(value = "prop") var prop: String by PrefixedProperty()
    

    【讨论】:

    • 你好!感谢您的回答。不幸的是,它对我不起作用。它说This annotation is not applicable to target 'member property with delegate' and use site target '@delegate'
    • 你应该使用这些依赖:com.fasterxml.jackson.core:jackson-core com.fasterxml.jackson.core:jackson-databind com.fasterxml.jackson.core:jackson-annotations com.fasterxml.jackson.module:jackson-module-kotlin
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2017-12-22
    • 1970-01-01
    • 2015-09-02
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多