英文:
Use a singleton class in kotlin, but call an external function to initialize it?
问题
我想封装Jackson
的ObjectMapper
类,将其转换为单例工具类。
但是单例类没有构造函数,我不知道应该怎么办?
我希望实现这样一个功能,请参见下面的伪代码:
object Jackson: ObjectMapper() = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
英文:
I want to wrap Jackson
s 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论