gpt4 book ai didi

java - 序列化/反序列化 ClassCastException : x cannot be cast to java. io.ObjectStreamClass

转载 作者:行者123 更新时间:2023-11-29 09:15:04 24 4
gpt4 key购买 nike

使用 Java 的 native 序列化,我间歇性地看到 ClassCastExceptions

java.lang.ClassCastException: myCompany.MyClass$MembershipServiceMethod cannot be cast to java.io.ObjectStreamClass

或(不太频繁)

java.lang.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass

当我反序列化特定不可变类的对象时。也就是说,对于特定的序列化表示总是抛出异常,但大多数对象都可以成功序列化和反序列化。

public final class ServiceInteractionImpl implements ServiceInteraction, Serializable {
private static final long serialVersionUID = 1L;

private final InteractionSource source;
private final long startTime;
private final InteractionType type;
private final ServiceMethod method;
private final long duration;
private final String accompanyingMessage;

public ServiceInteractionImpl(final ServiceMethod method,
final InteractionSource source,
final InteractionType type,
final long startTime,
final long duration,
final String accompanyingMessage) {
this.source = source;
this.startTime = startTime;
this.duration = duration;
this.type = type;
this.method = method;
this.accompanyingMessage = accompanyingMessage;
}

...

getters and canonical methods
}

其中 InteractionSource、InteractionType 和 ServiceMethod 是枚举。我无法在运行序列化和反序列化数百万个对象的 junit 测试的本地环境中复制它。

这里是写代码

    fileLock.lock();
try {
final File recordFile = new File(recordFileName);
boolean appendToFile = false;

if (recordFile.exists()) {
appendToFile = true;
}

final OutputStream fileOutputStream = new FileOutputStream(recordFileName, true);
final OutputStream buffer = new BufferedOutputStream(fileOutputStream);

ObjectOutput output;
if (appendToFile) {
output = new AppendableObjectOutputStream(buffer);
} else {
output = new ObjectOutputStream(buffer);
}

int localSerializedInteractionsCount = 0;

try {
for (final ServiceInteraction interaction : tempCollection) {
output.writeObject(interaction);
output.flush();
localSerializedInteractionsCount++;
rollBackCollection.remove(interaction);
}
} finally {
output.close();
serializedInteractionCount += localSerializedInteractionsCount;
}
} catch (IOException e) {
LOGGER.error("could not write to file", e);
//some roll-back code
} finally {
fileLock.unlock();
}

参见 Appending to an ObjectOutputStream对于 AppendableObjectOutputStream

非常感谢任何帮助。

最佳答案

如果在没有更新 serialVersionUID 的情况下更改了类定义,那么这些错误可能来自基于旧类定义的陈旧对象实例。

关于java - 序列化/反序列化 ClassCastException : x cannot be cast to java. io.ObjectStreamClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036603/

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