[英]Java: how to serialize a 3rd party library produced Java Object?
So I am using a proprietary java library in a project which I don't have access to source code. 所以我在项目中使用专有的java库,我无法访问源代码。
It throws a Message object, and obviously I can't implement Serializable. 它抛出一个Message对象,显然我无法实现Serializable。 It's generated throughout runtime.
它是在整个运行时生成的。
what are my options? 我有什么选择? Is there a way to serialize the Message object into a byte array and back into the object?
有没有办法将Message对象序列化为字节数组并返回到对象中?
UPDATE: I was able to serialize the object to JSON ( http://code.google.com/p/json-io/ ) but couldn't convert it back to an object as it returns null. 更新:我能够将对象序列化为JSON( http://code.google.com/p/json-io/ ),但无法将其转换回对象,因为它返回null。 So I am trying to convert it to byte array using the code below.
所以我试图使用下面的代码将其转换为字节数组。 Still not working.
还是行不通。
public byte[] toByteArray (Object obj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray ();
}
catch (IOException ex) {
//TODO: Handle the exception
}
return bytes;
}
public Object toObject (byte[] bytes)
{
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
}
catch (IOException ex) {
//TODO: Handle the exception
}
catch (ClassNotFoundException ex) {
//TODO: Handle the exception
}
return obj;
}
您可以编写一个可序列化的包装器,并存储重新创建Message对象所需的所有内容。
Sure, you just can't use the java.lang.Serializable
mechanism. 当然,你不能使用
java.lang.Serializable
机制。
Choose any format: XML, JSON, protocol buffer , or something else that might work for you. 选择任何格式:XML,JSON, 协议缓冲区或其他可能适合您的格式。
Now you're responsible for both ends of the conversation: serialization and deserialization. 现在,你负责对话的两端:序列化和反序列化。
XStream是一种方法。
如果对象是Java bean,则可以使用java.beans.XMLEncoder
和java.beans.XMLDecoder
进行序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.