大家都知道,定制自己的类的Serialization行为的方式是自己的类实现2个过程readObject和writeObject。我想不明白的是,为什么这个地方框架设计者没有设计成一个接口,接口里包含这两个重要的过程。相反,设计者用了最令人疑惑的方式,在类里加入这2个Private的过程,然后框架用Reflection来调用这2个过程。
有高手明白其中的奥妙吗?来自:http://blog.csdn.net/DancingCalf

解决方案 »

  1.   

    好像不是你说的这样的吧, 去看看Serializable接口!
    http://www.javacoffeebreak.com/articles/serialization/index.htmlpublic class TestObjectSerailizable implements Serializable { public static void main(String[] args) throws Exception  {
    File f = File.createTempFile("testser", "data");
    Ser s1 = new Ser(true, 1, "String var", "transient String var");
    s1.print();
    ObjectOutputStream dos = new ObjectOutputStream(new FileOutputStream(f));
    dos.writeObject(s1);
    dos.flush();
    dos.close();

    ObjectInputStream ois=  new ObjectInputStream(new FileInputStream(f));
    Ser s2 = (Ser) ois.readObject();
    s2.print();
    }

    class Ser implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -836219905694547906L;
    String varStr;
    int varInt;
    boolean varBool;
    transient String varStr2;
    /**
     * @param varBool
     * @param varInt
     * @param varStr
     * @param varStr2
     */
    public Ser(boolean varBool, int varInt, String varStr, String varStr2) {
    super();
    this.varBool = varBool;
    this.varInt = varInt;
    this.varStr = varStr;
    this.varStr2 = varStr2;
    }

    public void print() { 
    System.out.println("[varStr:" + varStr + ",varInt:" + varInt + ",varBool:" + varBool + ",varStr2:" + varStr2);
    }
    }
    }