13

我已经开始阅读 Java 中的序列化以及其他语言中的一些内容,但是如果我有一个泛型类并且我想将它的一个实例保存到文件中怎么办。

代码示例

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

保存这种对象的最佳方法是什么?(当然在我真正的宗教课程中还有更多,但我只是想知道实际的想法。)

4

2 回答 2

25

需要Serializable像往常一样制作通用类。

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

如果字段是使用泛型类型声明的,您可能需要指定它们应该实现Serializable

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

请注意此处不常见的 Java 语法。

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

于 2013-05-31T07:46:20.400 回答
0

如果您不想(或不能)实现 Serializable 接口,可以使用 XStream。这是一个简短的教程

在你的情况下:

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)
于 2013-05-31T07:48:41.670 回答