How to serialize a generic class in Java?

前端 未结 2 1097
孤街浪徒
孤街浪徒 2020-12-31 10:57

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.

相关标签:
2条回答
  • 2020-12-31 11:14

    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)
    
    0 讨论(0)
  • 2020-12-31 11:21

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

    0 讨论(0)
提交回复
热议问题