Leolian
Leolian

Reputation: 201

How to serialize a generic class in Java?

I have started to read about serialization in Java and little bit in other languages too, but what if I have a generic class and I want to save a instance of it to file.

code example

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

Whats the best way to save this kind of Object? (Of course there is more in my real ceneric class, but I'm just wondering the actual idea.)

Upvotes: 16

Views: 20746

Answers (2)

Grzegorz Żur
Grzegorz Żur

Reputation: 49231

You need to make generic class Serializable as usual.

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

If fields are declared using generic types, you may want to specify that they should implement Serializable.

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

Please be aware of uncommon Java syntax here.

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

Upvotes: 30

Burkhard
Burkhard

Reputation: 14738

If you don't 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)

Upvotes: 1

Related Questions