有一些方法来序列化或反序列化的Java对象...有没有办法知道哪种类型的java对象一旦被反序列化就被发送了?
准备字节发送:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
bos.close();
}
catch(Exception ex)
{
}
从字节创建对象:
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try
{
in = new ObjectInputStream(bis);
Object o = in.readObject();
if (in != null)
{
in.close();
}
}
catch (Exception ex)
{
}
}
但是,如果有人想通过网络发送不同类型的对象是否有办法知道哪种类型的对象已被发送。我想有可以选择创建一个类,然后序列化和反序列化它。
class SerialObject
{
String type;
Object object;
}
'如果(在你的! = null)in.close'应该在finally块中。就目前而言,'in.close()'不一定是调用的,如果执行,'in!= null'将始终为真。 –