Check for APIs that need to be serializable

Whem writing an API in Java often the classes you write need to be serialized, for example to transfer them using RMI. That means every class has to implement the serializable Interface. It is only a marker Interface but still it needs to be there. Why the property of being serializable is not inherited from the Object class has been the point of discussion elsewhere: Stackoverflow – Why java needs serializable interface

So what is the problem here?

Well, during development you realize that you API needs to be extended. Some classes are missing, so you start adding new classes. Then it happens, you forget to add the

but your Unit-Tests will show you everything is fine (if you do not do the serialization in your code). You can compile the code, build everything and so you will only get the

when doing integration tests or in production if your Unit-tests are the only tests that are done before moving to production. (The thing about moving to production with only Unit-tests sounds terrible but it is the sad truth, that in many projects there is no test stage)

So what can you do about it? Well I wrote a Unit-test that checks every class in a package (you API classes) if it implements the Serializable interface. That is what I wanted to share with you:

So how is it done?

First we need to get all the files in the types package “com.huetter.api.types”. To get the files in the package we treat the package name as the file path (that it is). The ContextClassLoader helps to do this when you put the Unit-Test in the same package. Then we filter out any directories that may be listed there. So now we have the list of files that are in the package.  Now we can use the URLClassLoader to load the java classes and test them using the

Serializable.class.isAssignableFrom method.

If the class is a superclass (or superinteface) of Serializable it will return true. So we have a check if a class implements Serializable. As the test iterates over all classes in the package, in case I forgot to add the “implements Serializable” the test will fail. So I can be assured, if the test is “green”, all classes are serializable.

Problem solved, the failing test will show you that you forgot to add the Serializable-Interface!

Did you solve the same problem or something similar? Please leave a comment!