1) creating an object. 2) serializing and then 3) deserializing.
This list is not complete; you also need initialization. Consider the example:
class CanBeSerialized implements Serializable {
private String a; // serializable
private Thread t; // not serializable
}
class CannotBeSerialized implements Serializable {
private String a; // serializable
private Thread t = new Thread(); // not serializable
}
You can serialize and deserialize the first one, but you'll get NotSerializableException
on the second. To complicate the matter further, if interfaces are used, you can never tell if a class will pass serialization, as it's the concrete object of the class behind this interface that will be streamed:
class PerhapsCanBeSerializedButYouNeverKnow implements Serializable {
private Runnable r; // interface type - who knows?
}
Provided that you could guarantee the following for all your classes and classes used by your classes to be tested:
- default constructor exists,
- no interface types in fields,
then you could automatically create and initialize them by reflection, and then test serialization. But that is a really hard condition, isn't it? Otherwise, proper initialization is down to manual work.
You could use reflection in a different way: iterating through a list of Class
objects you want to check, getting the Field[]
for them, and verifying if they're transient (Field.getModifiers()
) or if they implement Serializable
directly (Field.getType().getInterfaces()
) or indirectly (via a super interface or class). Also, consider how deep you want to check, depending on how deep your serialization mechanism works.
As Ryan pointed out correctly, this static serialization check would fail if the code was evil enough:
class SeeminglySerializable implements Serializable {
// ...
private void writeObject/readObject() {
throw new NotSerializableException();
}
}
or just if readObject()/writeObject()
were badly implemented. To test against this kind of problems, you need to actually test the serialization process, not the code behind it.