简体   繁体   中英

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.)

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 {...}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM