在Kotlin中使用单例类,但调用外部函数来初始化它?

huangapple go评论163阅读模式
英文:

Use a singleton class in kotlin, but call an external function to initialize it?

问题

我想封装JacksonObjectMapper类,将其转换为单例工具类。

但是单例类没有构造函数,我不知道应该怎么办?

我希望实现这样一个功能,请参见下面的伪代码:

object Jackson: ObjectMapper() = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
英文:

I want to wrap Jacksons ObjectMapper class and turn it into a single instance tool class.

But the singleton class has no constructor, I don't know what should I do?

I hope to achieve such a function, see the pseudo code below:

object Jackson: ObjectMapper() = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)

答案1

得分: 2

我认为最简单的方法是将ObjectMapper实例包装在一个命名对象中:

object Jackson {
    val mapper = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
}

然后使用Jackson.mapper访问它。我不知道更简洁的方法来创建或使用Java类的单例。

英文:

I assume the most straightforward way would be to just wrap the ObjectMapper instance in a named object:

object Jackson {
    val mapper = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
}

And access it with Jackson.mapper. I am not aware of a more concise way to create or use a singleton for a java class.

huangapple
  • 本文由 发表于 2023年3月9日 22:56:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定