Java反序列函数,Java-反序列化InvalidClassException(没有有效的构造函数)

I'm trying to serialize an object and then deserialize it after sending its data to a client program.

Here's an example of how the object's inheritance works. The object I'm serializing and deserializing is person.

Living -> Animal -> NPC -> Person -> Child

Living, Animal, and NPC do not implement Serializable. I can not change those three classes. Person and Child do implement Serializable. Person and Living are also abstract classes. I can serialize a Person (who is a Child) just fine and send it, but when I attempt to deserialize a Person (who is a Child), I get an InvalidClassException on Child, saying "no valid constructor".

Why is this happening? Must Living, Animal, and NPC all implement Serializable?

解决方案

Good explanation is done in answers for following question

Deserializing an ArrayList. no valid constructor

Long story short - you need no-arg constructor for first nonserializable super class of your class, NPC in your case.

If you don't have an access to NPC and it doesn't contain no-arg constructor - then you can add one more 'fake' class to hierarchy which will choose the correct one. E.g.

class SomeClass extends NPC {

// will be called during deserialization

public SomeClass(){

// call custom constructor of NPC

super(null);

}

}

class Person extends SomeClass implements Serializable {

// ..

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值