有序列化或反序列化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;
}
最佳答案
我认为了解发送对象类型的唯一方法是在 java 中使用 InstanceOf 关键字。 java instanceof 运算符用于测试对象是否是指定类型(类或子类或接口(interface))的实例。 Java 中的 instanceof 也称为类型比较运算符,因为它将实例与类型进行比较。它返回 true 或 false。
class Demo{
public static void main(String args[]){
Demo s=new Demo();
System.out.println(s instanceof Demo);//true
}
}
此代码返回真。只需使用 InstanceOf 关键字。它真的很有帮助
关于java - 有没有办法知道反序列化后发送了哪种类型的java对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39570093/