簡體   English   中英

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

[英]How to serialize a generic class in Java?

我已經開始閱讀Java中的序列化以及其他語言中的一些,但是如果我有一個泛型類並且我想將它的實例保存到文件中該怎么辦。

代碼示例

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

什么是保存這種對象的最佳方法? (當然,在我真正的通用課程中還有更多內容,但我只是想知道實際的想法。)

需要像往常一樣制作泛型類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 {...}

如果您不希望(或不能)實現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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM