且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中测试类是否正确实现了Serializable(不仅是Serializable的实例)

更新时间:2023-02-13 18:18:16

最简单的方法是检查对象是否是java.io.Serializablejava.io.Externalizable的实例,但这并不能真正证明该对象确实是可序列化.

The easy way is to check that the object is an instance of java.io.Serializable or java.io.Externalizable, but that doesn't really prove that the object really is serializable.

唯一可以确定的方法是实际尝试.最简单的测试是这样的:

The only way to be sure is to try it for real. The simplest test is something like:

new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(myObject);

并检查它是否不会引发异常.

and check it doesn't throw an exception.

Apache Commons Lang 提供了一个更为简短的版本:

Apache Commons Lang provides a rather more brief version:

SerializationUtils.serialize(myObject);

再次检查异常.

您仍然可以更加严格,并检查它反序列化为与原始序列相同的内容:

You can be more rigourous still, and check that it deserializes back into something equal to the original:

Serializable original = ...
Serializable copy = SerializationUtils.clone(original);
assertEquals(original, copy);

以此类推.