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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…