Reliably convert any object to String and then back again

后端 未结 7 778
名媛妹妹
名媛妹妹 2020-12-02 13:35

Is there a reliable way to convert any object to a String and then back again to the same Object? I\'ve seen some examples of people converting them using toString()

7条回答
  •  伪装坚强ぢ
    2020-12-02 14:02

    Yes, it is called serialization!

     String serializedObject = "";
    
     // serialize the object
     try {
         ByteArrayOutputStream bo = new ByteArrayOutputStream();
         ObjectOutputStream so = new ObjectOutputStream(bo);
         so.writeObject(myObject);
         so.flush();
         serializedObject = bo.toString();
     } catch (Exception e) {
         System.out.println(e);
     }
    
     // deserialize the object
     try {
         byte b[] = serializedObject.getBytes(); 
         ByteArrayInputStream bi = new ByteArrayInputStream(b);
         ObjectInputStream si = new ObjectInputStream(bi);
         MyObject obj = (MyObject) si.readObject();
     } catch (Exception e) {
         System.out.println(e);
     }
    

提交回复
热议问题