将Parceler与带有构造函数的Kotlin数据类一起用于序列化 [英] Use of Parceler with Kotlin data class with constructor for serialization
问题描述
有没有一种方法可以对Kotlin数据类和构造函数使用 Parceler 进行序列化,而无需为每个字段使用@ParcelProperty
批注?
Is there a way to use Parceler with Kotlin data classes and constructor for serialization without using @ParcelProperty
annotation for each field?
如果我尝试使用像这样的库:
If I try and use library like this:
@Parcel
data class Valve @ParcelConstructor constructor(val size: Int)
我得到Error:Parceler: No corresponding property found for constructor parameter arg0
.但是,如果我添加@ParcelProperty("size")
,它就可以正常工作.
为什么会这样?
I get Error:Parceler: No corresponding property found for constructor parameter arg0
. But if I add @ParcelProperty("size")
it works just fine.
Why is that?
更新:
还有其他使用此库的方法.
我可以只删除@ParcelConstructor
批注,但随后会出现错误
Error:Parceler: No @ParcelConstructor annotated constructor and no default empty bean constructor found.
我认为(未经测试)我也可以使所有构造函数参数为可选参数并添加@JvmOverloads
,但这具有副作用,我必须检查该类的所有属性是否为空.
Update:
There are other another way to use this library.
I could just remove @ParcelConstructor
annotation, but then I will get error
Error:Parceler: No @ParcelConstructor annotated constructor and no default empty bean constructor found.
I think (haven't tested it) I also could make all constructor parameters optional and add @JvmOverloads
but that has a side effect that I have to check all properties of the class if they are null or not.
更新2 :
这对我有用:
Update 2:
This is what worked for me:
@Parcel
data class Valve(val size: Int? = null)
简而言之,生成的Java类必须具有默认的空构造函数.一种实现上述目的的方法是-所有变量都应具有默认值.
In short generated Java class must have default empty constructor. One way to achieve that is to do as above - all variables should have default values.
推荐答案
根据文档,默认情况下,Parceler适用于公共字段.但是通常的Kotlin data class
(如您的示例所示)实际上是传统的getter/setter bean",因为每个Kotlin属性都由一个私有字段和一个getter/[setter]表示.
According to the docs, Parceler by default works with public fields. But a usual Kotlin data class
(as in your example) is rather a "traditional getter/setter bean", since every Kotlin property is represented by a private field and a getter/[setter].
TL; DR:我认为这会起作用:
TL; DR: I think this will work:
@Parcel(Serialization.BEAN)
data class Valve(val size: Int = 10)
请注意默认值,它允许Kotlin自动生成一个额外的空构造函数,这是Java Been规范所必需的.
Note the default value, it allows Kotlin to automatically generate an additional empty constructor, which is required by the Java Been specification.
另一种方法是标记我们已经拥有的构造函数:
Another way would be to mark the constructor that we already have:
@Parcel(Serialization.BEAN)
data class Driver @ParcelConstructor constructor(val name: String)
特定文档: https://github.com/johncarl81/parceler#gettersetter-serialization
这篇关于将Parceler与带有构造函数的Kotlin数据类一起用于序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!