首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用kotlin-reflect对属性的Kotlin和反射

使用kotlin-reflect对属性的Kotlin和反射
EN

Stack Overflow用户
提问于 2018-10-03 19:58:02
回答 1查看 336关注 0票数 0

我使用kotlin-reflect在Kotlin数据类上进行反射

定义如下

代码语言:javascript
复制
@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,但当我尝试时

代码语言:javascript
复制
obj
  .javaClass
  .kotlin
  .declaredMemberProperties
  .first()
  .findAnnotation<JsonProperty>()

然后,不管我怎么尝试,我都会得到null

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

EN

回答 1

Stack Overflow用户

发布于 2018-10-03 20:58:56

我刚刚找到了答案:

使用java反编译器,注解显然不在字段或getter上,而是在构造器参数上

代码语言:javascript
复制
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作为构造函数参数时,我能够检索到注释

代码语言:javascript
复制
obj
    .javaClass
    .kotlin
    .constructors
    .first()
    .parameters
    .first()
    .findAnnotation<JsonProperty>()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52626548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档