如何解决“ NotSerializableException”?在单元测试“ LinearState”的简单实现时抛出 [英] How to resolve a "NotSerializableException" thrown when unit testing a plain implementation of "LinearState"
问题描述
我有一个 LinearState的简单实现,其中唯一的参数是UniqueIdentifier。我有一份简单的合同。
I have a plain implementation of "LinearState" where the only parameter is a UniqueIdentifier. I have a simple Contract to go with it.
但是,当我尝试通过单元测试进行测试时,我会不断收到 NotSerializabeException。
When I try to put it through unit testing, however, I keep getting "NotSerializabeException".
我正在使用Corda v4 Java模板。使用IntelliJ上的Gradle Runner测试设置。
I'm using the Corda v4 java template. Testing setup with Gradle Runner on IntelliJ.
我尝试使用@CordaSerializable注释类,并使用@ConstructorForDeserialization注释构造函数
I've tried annotating the class with @CordaSerializable, and the constructor with @ConstructorForDeserialization
@CordaSerializable
public class InvestorState implements LinearState {
private final UniqueIdentifier linearId;
@ConstructorForDeserialization
public InvestorState(UniqueIdentifier id) {
this.linearId = id;
}
...
}
Error log:
data(net.corda.core.contracts.ContractState) -> Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.
java.io.NotSerializableException: data(net.corda.core.contracts.ContractState) -> Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.
at net.corda.serialization.internal.amqp.ObjectSerializer$Companion.make(ObjectSerializer.kt:18)
at net.corda.serialization.internal.amqp.DefaultLocalSerializerFactory.makeNonCustomSerializer(LocalSerializerFactory.kt:240)
...
推荐答案
仅需两美分,以备将来参考:
来自Corda文档:
Just my two cents for future reference: From Corda documentation:
建议坚持Corda中的可序列化对象遵循以下规则,因为它们允许对不可变状态对象进行反序列化:
It is recommended that serializable objects in Corda adhere to the following rules, as they allow immutable state objects to be deserialised:
- 构造函数中每个属性的Java Bean getter,名称形式为getX。例如,对于构造函数参数foo,必须有一个名为getFoo()的getter。
如果foo是布尔值,则可以选择将getter称为isFoo()(这就是为什么必须使用参数名称编译该类的原因
If foo is a boolean, the getter may optionally be called isFoo() (this is why the class must be compiled with parameter names turned on)
- 一个构造函数,它采用您希望以序列化形式记录的所有属性。
这是序列化框架重建类实例的必需条件。
This is required in order for the serialization framework to reconstruct an instance of your class.
如果提供了多个构造函数,则序列化框架需要知道要使用哪个构造函数。 @ ConstructorForDeserialization 注释可用于指示哪个。
If more than one constructor is provided, the serialization framework needs to know which one to use. The @ConstructorForDeserialization annotation can be used to indicate which one.
对于Kotlin类,如果没有@ConstructorForDeserialization批注,将选择主构造函数。
For a Kotlin class, without the @ConstructorForDeserialization annotation, the primary constructor will be selected.
这篇关于如何解决“ NotSerializableException”?在单元测试“ LinearState”的简单实现时抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!