gpt4 book ai didi

java.io.InvalidClassException : local class incompatible:

转载 作者:IT老高 更新时间:2023-10-28 20:27:16 25 4
gpt4 key购买 nike

我创建了客户端和服务器,然后在客户端添加了一个用于序列化目的的类,然后只需转到我硬盘中客户端的文件夹并将其复制粘贴到服务器对应的位置,两个 classname. classclassname.java 分别。

它在我自己的笔记本电脑上运行良好,但是当我想在其他系统上继续工作时,当我打开项目文件夹并且客户端尝试连接到服务器后,出现以下错误:

Exception in thread "main" java.io.InvalidClassException: projectname.clasname; local class incompatible: stream classdesc serialVersionUID = -6009442170907349114, local class serialVersionUID = 6529685098267757690
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:562)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1582)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)

发生了什么事?是因为我使用旧版本的 IDE 运行程序吗?

编辑

import java.io.Serializable;
import java.net.URL;

public class KeyAdr implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;

public URL adr;
public String key;
}

最佳答案

如果一个类没有在代码中显式定义一个private static final long serialVersionUID,它会自动生成,不保证不同机器生成相同的id;看起来这正是发生的事情。此外,如果类在任何方面都不同(使用不同版本的类),自动生成的 serialVersionUID 也会不同。

来自 Serializable 接口(interface)的 docs :

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

你应该在类定义中定义一个serialVersionUID,例如:

class MyClass implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
...

关于java.io.InvalidClassException : local class incompatible:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com