How to serialize a common class in Java?

I started reading about serialization in Java and a few other languages, but what if I have a generic class and I want to save its instance to a file.

code example

public class Generic<T> { private T key; public Generic<T>() { key = null; } public Generic<T>(T key) { this.key = key; } } 

What is the best way to save this kind of object? (Of course, in my real class, but I'm just interested in the real idea.)

+9
java generics serialization
source share
2 answers

You need to make the regular Serializable class as usual.

public class Generic<T> implements Serializable {...}

If fields are declared using common types, you may wish to indicate that they should implement Serializable .

public class Generic<T extends Serializable> implements Serializable {...}

Check out the unusual Java syntax here.

public class Generic<T extends Something & Serializable> implements Serializable {...}

+20
source share

If you do not want (or cannot) implement the Serializable interface, you can use XStream. Here is a short tutorial .

In your case:

 XStream xstream = new XStream(); Generic<T> generic = ...;//whatever needed String xml = xstream.toXML(generic); //write it to a file (or use xstream directly to write it to a file) 
0
source share

All Articles