通过传递引用vs返回引用来反序列化对象

时间:2011-06-04 07:42:16

标签: java serialization

我只是想回读一个我写入文件的对象。我有两个功能。

public static Serializable_test deSerialize_object(String filename)

{

    File a = new File(filename);
    ObjectInputStream in = null;
    try{
     in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
    }catch(IOException e){
        e.printStackTrace();
    }
    Serializable_test obj1 = null;
    try{

    obj1 = (Serializable_test) in.readObject();
    in.close();

    }catch(IOException e){
        e.printStackTrace();
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }
    return obj1;

}
public static void deSerialize_object(Serializable_test obj,String filename){
    File a = new File(filename);
    //int objcount = 0;
    ObjectInputStream in = null;
    try{
     in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
    }catch(IOException e){
        e.printStackTrace();
    }
    try{
        obj = (Serializable_test) in.readObject();
        in.close();
    }catch(EOFException e){
        System.out.println("END of object files reached");
    }catch(IOException e){
        e.printStackTrace();
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }


}

第一种方法工作正常......第二种方法应该将读取对象分配给传递的引用但它根本不起作用(传递的对象的状态保持与初始化状态相同,而它应该是是读取对象的那个)代码中有什么问题吗?。

3 个答案:

答案 0 :(得分:3)

这是因为Java references are passed by value。您的第二个方法接收对象的引用副本,因此在第二个方法中更新该引用不会影响原始对象。

最简单的解决方案是返回从序列化流中读取的对象。如果确实想要使用反序列化对象更新现有对象,请提供mutator update方法,该方法将传入对象的字段设置为新读取对象的字段。

public static void deSerialize_object(Serializable_test obj, String filename) {
    File a = new File(filename);     
    ObjectInputStream in = null;
    try {
        ObjectInputStream in =
            new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
        Serializable_test newObj = (Serializable_test) in.readObject();
        obj.update(newObject);
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) in.close();
    }
}

还要确保关闭finally块中的资源。

答案 1 :(得分:1)

该行

obj =  (Serializable_test) in.readObject();

创建一个新对象,并在obj变量中放置对该对象的引用。

您有效地覆盖传递给方法的引用。

在这些情况下,我让对象使用“copyFrom”方法或“readFromStream”方法自行更新。但我更喜欢基于功能的方法。

答案 2 :(得分:1)

在Java中,对象的引用按值传递。

解决方法类似于

// obj must be an initialized Serializable_test[1] before you call

public static void deSerialize_object(Serializable_test[] obj,String filename){
    ...
    obj[0] = (Serializable_test) in.readObject();
    ...
}

但我不明白为什么你不想只返回参考文献。