Just like the title says, is there a way to check if an object is serializable, and if not, make it so at run time?
As others have said... Short Answer is No.
You can absolutely add an interface to any old object at runtime by using Proxy objects as described at http://download.oracle.com/javase/6/docs/technotes/guides/reflection/proxy.html . This includes java.io.Serializable too. However, in order for a proxy object to be useful, it must maintain an internal reference to the original object, which in your case does not implement Serializable. The only way your proxy object could be serialized is by making the internal reference to the original object a transient field and that wouldn't do you much good at all.
Further, after examining your comments, it looks like java serialization is definitely not what you want and you really just want to serialize to some string format. Others have suggested various solutions, but IMO if you want the least amount of fuss, go with XStream: http://xstream.codehaus.org/tutorial.html .
Short answer - no.
Longer answer - yes, using byte-code manipulation, for example with asm. But you should really consider whether this is needed. Serialization is a serious matter (Effective Java has a whole chapter on serialization)
Btw, there are alternatives to binary serialization, that do not require the object implementing Serializble
(as pointed by Jacob in the comments):
- XML -
java.beans.XMLEncoder.encode(..)
is the xml version ofObjectOutputStream
- JSON - frameworks like Jacskon, Gson let you serialize an object with one line.
Whoa. Why would you need it to be checked at runtime? Isn't it easier to ensure it at compile time? Using a code just like this.
public void someMethod(Serializable serializable){
}
Or you can make it more complex.
public interface SerializableInterface implements Serializable{
// bla-bla
}
public void someMethod(SerializableInterface serializable){
}
Aside from existing good answers, another question is whether you specifically need Java Serializable for specific framework, or just need to be able to serializer objects. For latter there are many many more choices than JDK default one; and for many use cases alternatives are much better than JDK one.
If you don't specifically need JDK one, using JSON or XML based serialization is often a good choice.
Checking at run time? Sure. "if (someObject instanceof Serializable) ...".
You want to change the definition of an object at run time? There is very rarely a good reason to want to do this. Maybe there's a way to do this with reflection, but I've never had a reason to want to do such a thing. What are you trying to accomplish?