Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

serialization - how to test in Java that a class implements Serializable correctly (not just is an instance of Serializable)

I am implementing a class to be Serializable (so it's a value object for use w/ RMI). But I need to test it. Is there a way to do this easily?

clarification: I'm implementing the class, so it's trivial to stick Serializable in the class definition. I need to manually serialize/deserialize it to see if it works.

I found this C# question, is there a similar answer for Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 provides a rather more brief version:

SerializationUtils.serialize(myObject);

and again, check for the exception.

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);

and so on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...