【问题标题】:serialization using generics使用泛型进行序列化
【发布时间】:2013-12-19 02:10:48
【问题描述】:

下面是一段序列化对象的代码,但使用了泛型。 我执行此方法时没有创建 .ser 文件。我敢肯定我在这里遗漏了一些重要的泛型概念。请帮帮我!

public <T> void saveToDisk(List<T> objectlist) {
    // TODO Auto-generated method stub
    System.out.println(path);
    if ("domain_pojo.Customer".equals(objectlist.getClass().getName()))
        file = "/customer.ser";
    else if ("domain_pojo.Employees"
            .equals(objectlist.getClass().getName()))
        file = "/employee.ser";
    else if ("domain_pojo.Orders".equals(objectlist.getClass().getName()))
        file = "/order.ser";

    try {
        FileOutputStream fos = new FileOutputStream(path + file);
        // Create ObjectOutputStream to write object
        ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
        // Write object to file
        System.out.println("Size of objectlist is :" + objectlist.size());
        // objectlist.add(null);
        for (T obj : objectlist) {
            objOutputStream.writeObject(obj);
            objOutputStream.reset();
        }
        objOutputStream.close();
    } catch (IOException e) {
        new FileParsingException(e, e.getMessage());
    }
}

【问题讨论】:

  • “文件”在哪里声明,如果所有三个条件都失败,它有什么价值?

标签: java object serializable


【解决方案1】:

if ("domain_pojo.Customer".equals(objectlist.getClass().getName()))

这一行总是假的(并且情况与其他 else IF 块相同)因为objectlist.getClass() 的值总是 java.util.List。

您应该改为传递 Class&lt;T&gt; clazz 并在比较中使用它。

在相关的说明中,最好让类实现一些返回文件名的接口方法,而不是像这样的硬编码。

【讨论】:

  • +1,但如果您大声提到“类型擦除”可能会更好;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2017-01-04
相关资源
最近更新 更多