一旦方法返回,传递给方法的列表和反序列化变为空

Jul*_*les 0 java generics collections serialization

我有一个方法:

static <E extends NotesAttached> void deserialise(List<E> list, String type) {
    String fileName = "C:/temp/SalesModel." + type + ".list.ser";
    try {
        FileInputStream serFile = new FileInputStream(fileName);
        ObjectInputStream in = new ObjectInputStream(serFile);
        list = (List<E>) in.readObject();
        in.close();
        serFile.close();
        System.out.println(type + "s deserialised successfully, " + list.size() + " retrieved");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

我称之为:

    List<Deal> deals = new ArrayList<Deal>();
    deserialise(deals, "Deal");
    System.out.println("Number of deals deserialised: " + deals.size());
Run Code Online (Sandbox Code Playgroud)

该列表在方法中填充,但是当它返回时,它是空的.我不明白为什么,如果有人能解释,我会很感激.

输出如下:

成功反序列化,2522检索反序列化的交易数量:0

Jon*_*eet 5

您已反序列化的列表不会"变空" - 但deals变量不会引用您刚刚反序列化的列表...它指的是在调用方法之前它所执行的相同的空列表.更改list方法中参数的值不会对您传递的参数产生任何影响,因为Java使用pass by value.

void返回列表时,最好不要使用方法:

static <E extends NotesAttached> List<E> deserialise(String type)
        throws IOException, ClassNotFoundException {
    String fileName = "C:/temp/SalesModel." + type + ".list.ser";
    FileInputStream serFile = new FileInputStream(fileName);
    ObjectInputStream in = new ObjectInputStream(serFile);
    try {
        List<E> list = (List<E>) in.readObject();
        System.out.println(type + "s deserialised successfully, " + list.size() + " retrieved");
        return list;
    } finally {
        // See notes
        in.close();
        serFile.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

List<Deal> deals = deserialise(deals, "Deal");
System.out.println("Number of deals deserialised: " + deals.size());
Run Code Online (Sandbox Code Playgroud)

你需要处理ClassNotFoundExceptionIOException,但最好不要在方法之外处理它们 - 你几乎肯定不想只是捕获它们,转储堆栈跟踪并继续,好像什么都没有出错.

不太对,因为你真的想关闭流而不管其他错误.如果可以使用Java 7,则可以使用try-with-resources语句:

static <E extends NotesAttached> List<E> deserialise(String type)
        throws IOException, ClassNotFoundException {
    String fileName = "C:/temp/SalesModel." + type + ".list.ser";
    try (FileInputStream serFile = new FileInputStream(fileName),
         ObjectInputStream in = new ObjectInputStream(serFile)) {
        List<E> list = (List<E>) in.readObject();
        System.out.println(type + "s deserialised successfully, " + list.size() + " retrieved");
        return list;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你坚持使用Java 6,我可能会使用嵌套的try/finally块 - 或者关闭它FileInputStream,因为ObjectInputStream它不会保留任何非托管资源.