使用Java的本機序列,我看到間歇的ClassCastExceptions序列化/反序列化ClassCastException異常:X不能轉換到java.io.ObjectStreamClass中
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
任何幫助。
在這裏讀取行之間,我看到兩個不同的運行時環境 - 它在一個失敗,但在另一個運行。有關環境差異的細節? – 2012-09-14 05:50:18
@RichardSitze只有一個運行時,但我已經從這個問題上移開,並且現在無法有效地參與關於它的討論。 – Joffer 2012-09-17 23:29:41