2

I am trying to serialize a non-serializable object in Java. A standard solution is to implement writeObject and readObject methods for that class.

In my case, though, the the class of the object to be serialized is in a JAR file, so I cannot change it to implement the readObject and writeObject methods.

Also, the class in the JAR is a final class.

Is there any way to serialize an object in this case?

Sid
  • 4,893
  • 14
  • 55
  • 110
  • *"Thanks, Siddharth"* Leave such noise out of questions. – Andrew Thompson Apr 16 '13 at 11:21
  • @AndrewThompson, I agree, thanks for editing. – Sid Apr 16 '13 at 11:21
  • 1
    Is there any reason why you couldn't extend the class in the jar to a child class, then implement serializable in the child class? – David Apr 16 '13 at 11:23
  • @david99world, The class is final in the JAR. Sorry I forgot to mention. Will edit my question likewise. – Sid Apr 16 '13 at 11:25
  • 1
    If you can use an intermediary format (like xml), you could use xstream or another serialization framework. – NilsH Apr 16 '13 at 11:28
  • 1
    i found similar question on SO. May it help you. http://stackoverflow.com/questions/2114105/in-java-is-it-possible-to-add-the-serializable-interface-to-class-that-doesnt – Rais Alam Apr 16 '13 at 11:52

2 Answers2

2

Extend the jar class something like this

public class YourSerializableClass extends Jar Class implements Serializable

Basically you need to subclass your jar class and make it to imple serializable

Update:-

If class is final you can try removing that modifier and then use above approach otherwise probably you need to use byte code manipulation. here is the link which can give you pointers to remove final modifier

Using reflection to change static final File.separatorChar for unit testing?

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
  • I forgot to mention that the class is a final class in my JAR. I have edited the question. Thanks for your response. – Sid Apr 16 '13 at 11:26
2

You can use AspectJ or a form of byte-code manipulation using tools like BCEL or ASM to enhance that class with the readObject and writeObject methods.

dan
  • 13,132
  • 3
  • 38
  • 49