可靠地将任何对象转换为字符串,然后再返回 [英] Reliably convert any object to String and then back again

查看:42
本文介绍了可靠地将任何对象转换为字符串,然后再返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种可靠的方法可以将任何对象转换为字符串,然后再返回到同一个对象?我见过一些例子,人们使用 toString() 转换它们,然后将该值传递给构造函数以再次重建对象,但并非所有对象都有这样的构造函数,因此该方法不适用于所有人案件.会怎样?

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() and then passing that value into a constructor to reconstruct the object again but not all objects have a constructor like this so that method wont work for all cases. What way will?

推荐答案

是的,它叫 序列化

 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);
 }

这篇关于可靠地将任何对象转换为字符串,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆