如何序列化Java中的泛型类? [英] How to serialize a generic class in Java?

查看:1081
本文介绍了如何序列化Java中的泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读关于Java中的序列化和其他语言中的一点点,但如果我有一个泛型类并且我想将它的一个实例保存到文件中,该怎么办。



代码示例

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

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

need 像通常那样创建泛型类 Serializable

public class Generic< T>实现Serializable {...}



如果使用泛型类型声明了字段,那么可能希望他们应该实现 Serializable



public class Generic< T extends Serializable>实现Serializable {...}



请注意不常用的Java语法。



public class Generic< T extends Something&序列化>实现Serializable {...}


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.

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.

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

这篇关于如何序列化Java中的泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆