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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16852247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:10:33  来源:igfitidea点击:

How to serialize a generic class in Java?

javagenericsserialization

提问by Leolian

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

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

回答by Grzegorz ?ur

You needto make generic class Serializableas usual.

需要Serializable像往常一样制作泛型类。

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

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

If fields are declared using generic types, you may wantto specify that they should implement Serializable.

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

public class Generic<T extends Serializable> implements 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 {...}

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

回答by Burkhard

If you don't want (or cannot) implement the Serializable interface, you can use XStream. Here is a short tutorial.

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

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)