简体   繁体   English

如何在Java中序列化泛型类?

[英]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. 我已经开始阅读Java中的序列化以及其他语言中的一些,但是如果我有一个泛型类并且我想将它的实例保存到文件中该怎么办。

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. 需要像往常一样制作泛型类Serializable

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

If fields are declared using generic types, you may want to specify that they should implement Serializable . 如果使用泛型类型声明字段,则可能需要指定它们应实现Serializable

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

Please be aware of uncommon Java syntax here. 请注意这里不常见的Java语法。

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

If you don't want (or cannot) implement the Serializable interface, you can use XStream. 如果您不希望(或不能)实现Serializable接口,则可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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