use*_*186 36 java string object
有没有可靠的方法将任何对象转换为String然后再返回到同一个对象?我已经看到一些人们使用转换它们toString()然后将该值传递给构造函数来重新构建对象的示例,但并非所有对象都有这样的构造函数,因此该方法不适用于所有情况.会怎么样?
And*_*rew 62
是的,它被称为序列化!
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 15
这是代码:
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(stringList);
so.flush();
redisString = new String(Base64.encode(bo.toByteArray()));
}
catch (Exception e) {
e.printStackTrace();
}
try {
byte b[] = Base64.decode(redisString.getBytes());
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
List<String> stringList2 = (List<String>)si.readObject();
System.out.println(stringList2.get(1));
}
catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
没有人会在所有情况下都有效.例如,对象可以包含对处理其状态的其他JVM的引用,并且此状态可能无法供您恢复.
您将要遇到的其他问题包括开放流,侦听套接字以及来自外部世界的几乎任何其他问题.
有没有必要重复最多至少两个Java核心工程师说,序列化是最大的错误之一在Java中的最糟糕的特点,那就是,定稿后.(尽管我喜欢序列化,但它很方便.但它并不总能奏效.)
| 归档时间: |
|
| 查看次数: |
59347 次 |
| 最近记录: |