2

使用 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的附加到 ObjectOutputStream

非常感谢任何帮助。

4

1 回答 1

0

如果类定义更改而没有更新 serialVersionUID,则这些错误可能来自基于旧类定义的陈旧对象实例。

于 2012-04-05T22:18:49.797 回答