有没有一种方法可以对Kotlin数据类和构造函数使用Parceler进行序列化,而不对每个字段使用@ParcelProperty注释?

如果我try 像这样使用库:

@Parcel
data class Valve @ParcelConstructor constructor(val size: Int)

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?

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.

Update 2:
This is what worked for me:

@Parcel
data class Valve(val size: Int? = null)

简而言之,生成的Java类必须有默认的空构造函数.实现这一点的一种方法是如上所述——所有变量都应该有默认值.

推荐答案

根据文档,Parceler默认使用公共字段.但通常的Kotlin data class(如您的示例中)相当于一个"传统的getter/setter bean",因 for each Kotlin属性都由一个私有字段和一个getter/[setter]表示.

TL; DR: I think this will work:

@Parcel(Serialization.BEAN)
data class Valve(val size: Int = 10)

Note the default value, it allows Kotlin to automatically generate an additional empty constructor, which is required by the Java Been specification.

另一种方法是标记我们已经拥有的构造函数:

@Parcel(Serialization.BEAN)
data class Driver @ParcelConstructor constructor(val name: String)

The specific document: https://github.com/johncarl81/parceler#gettersetter-serialization

Kotlin相关问答推荐

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

Kotlin:有限的并行性并不是限制并行性

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

将一个列表元素分组为多个组(indexBy)

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

使用启动或使用 coroutineScope 启动协程之间的区别

如何限制 Kotlin 中的枚举?

如何使用 Findbugs 避免 kotlin 文件

基类中的 ViewModelProviders.get(...)

为什么我在使用 Jetpack Compose clickable-Modifier 时收到后端内部错误:Exception during IR lowering error?

如何使用 Coil 从 URL 获取位图?

runOnUiThread 没有调用

Jetpack Compose – LazyColumn 不重组

从 Spring WebFlux 返回 Flux 返回一个字符串而不是 JSON 中的字符串数组

Kotlin Native如何将字节数组转换为字符串?

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

Android EditText 协程go 抖操作符,如 RxJava

Android Studio - java.io.IOException:无法生成 v1 签名

Android Jetpack Compose - 图像无法zoom 到框的宽度和高度

如何在 Fragment 中使用 Anko DSL?