使用泛型的序列化

时间:2013-12-03 06:06:33

标签: java object serializable

下面是一段用于序列化对象但使用泛型的代码。 我执行此方法时没有创建.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());
    }
}

1 个答案:

答案 0 :(得分:2)

  

if(“domain_pojo.Customer”.equals(objectlist.getClass()。getName()))

此行始终为false(并且大小写与其他其他IF块相同),因为objectlist.getClass()的值始终为java.util.List。

您应该通过Class<T> clazz并在比较中使用它。

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

相关问题