How to serialize a generic class in Java?

ⅰ亾dé卋堺 提交于 2019-12-30 03:10:49

问题


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


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/16852247/how-to-serialize-a-generic-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!