Kotlin和使用Kotlin-reflect对属性的思考

时间:2018-10-03 11:58:02

标签: reflection kotlin jackson

我正在使用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数据类(即在杰克逊数据绑定中定义的@JsonProperty)上使用反射来访问属性注释

1 个答案:

答案 0 :(得分:0)

我刚刚找到了答案:

使用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的Refection作为构造函数参数时,我能够检索注释

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