serialization/deserialization mechanism

后端 未结 5 855
粉色の甜心
粉色の甜心 2021-01-13 04:42

Say, I have a class X which has a field value, that is,

class X implements Serializable {
    private i         


        
5条回答
  •  时光说笑
    2021-01-13 05:24

    You don't need to have getters/setter to serialize/deserialize using java serialization, for example, check this code:

    public class Main {
    
        public static class Q implements Serializable {
            private int x;
            public Q() {
                x = 10;
            }
            public void printValue() {
                System.out.println(x);
            }
        }
    
        public static void main(String[] args) throws Exception {
            Q q = new Q();
            FileOutputStream fos = new FileOutputStream("c:\\temp.out");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(q);
            fos.close();
    
            FileInputStream fis = new FileInputStream("c:\\temp.out");
            ObjectInputStream oin = new ObjectInputStream(fis);
            Q q2 = (Q)oin.readObject();
            fis.close();
            q2.printValue();
    
        }
    }
    

提交回复
热议问题