【问题标题】:Kotlin and reflection on properties using kotlin-reflectKotlin 和使用 kotlin-reflect 对属性进行反射
【发布时间】:2018-10-03 11:58:01
【问题描述】:

我正在使用kotlin-reflect 反射 Kotlin 数据类

定义是这样的

@JsonIgnoreProperties(ignoreUnknown = true)
data class TopicConfiguration(
    @JsonProperty("max.message.bytes") var maxMessageBytes: Long? = null,
    @JsonProperty("compression.type") var compressionType: String? = null,
    @JsonProperty("retention.ms") var retentionMs: Long? = null
)

我想使用反射获得@JsonProperty,但是当我尝试时

obj
  .javaClass
  .kotlin
  .declaredMemberProperties
  .first()
  .findAnnotation<JsonProperty>()

然后无论我尝试什么,我都会得到null

如何使用 Kotlin 数据类(即在 jackson 数据绑定中定义的 @JsonProperty)上的反射访问属性注释

【问题讨论】:

    标签: reflection kotlin jackson


    【解决方案1】:

    我刚刚找到了答案:

    使用 java-decompiler,很明显注解不是在字段或 getter 上,而是在构造函数参数上

    public TopicConfiguration(@Nullable @JsonProperty("max.message.bytes") Long maxMessageBytes, @Nullable @JsonProperty("compression.type") String compressionType, @Nullable @JsonProperty("retention.ms") Long retentionMs)
      {
        this.maxMessageBytes = maxMessageBytes;this.compressionType = compressionType;this.retentionMs = retentionMs;
      }
    

    当我使用 Kotlin 的反射作为构造函数参数时,我能够检索注解

    obj
        .javaClass
        .kotlin
        .constructors
        .first()
        .parameters
        .first()
        .findAnnotation<JsonProperty>()
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多