【发布时间】:2012-04-05 21:58:31
【问题描述】:
使用 Java 的本机序列化,我间歇性地看到 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();
}
有关 AppendableObjectOutputStream,请参阅 Appending to an ObjectOutputStream
非常感谢任何帮助。
【问题讨论】:
-
在字里行间阅读,我看到了两种不同的运行时环境——它在一个环境中失败,但在另一个环境中运行。环境之间差异的详细信息?
-
@RichardSitze 只是一个运行时,但我已经从这个问题继续前进,现在无法有效地参与有关它的讨论。
标签: java serialization deserialization