简体   繁体   English

将字节数组分配给Java对象

[英]Assigning byte array to Java Object

Is it possible to assign a byte arra(which are received via a tcp socket) directly to a Java Object without parsing the data? 是否可以在不解析数据的情况下直接将字节arra(通过tcp套接字接收)分配给Java对象?

In c it is possible to assign bytes directly to a struct, is that possible in java? 在c中可以直接将字节分配给结构,在java中可以吗?

It is not possible to assign a byte array to an object in java and have all the member variables populated automatically, but it is possible to get a java object out of a byte array using serialization. 不可能将字节数组分配给Java中的对象并自动填充所有成员变量,但是可以使用序列化从字节数组中获取Java对象。

You can use ObjectInputStream and ObjectOutputStream to get objects in and out of a stream. 您可以使用ObjectInputStreamObjectOutputStream将对象ObjectOutputStream和移出流。 To get one out of a byte array wrap a ByteArrayInputStream in a ObjectInputStream . 要从字节数组中取出一个,请在ObjectInputStream包装一个ByteArrayInputStream The object must implement the Serializable interface. 该对象必须实现Serializable接口。 This should help you avoid parsing byte arrays manually. 这应该可以帮助您避免手动解析字节数组。

ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
MyObject o = (MyObject) in.readObject();

If you are reading data that is not a serialized java object you can add methods to the object to help the serialization. 如果您正在读取的数据不是序列化的Java对象,则可以向该对象添加方法以帮助序列化。

From the javadoc for ObjectInputStream 从javadoc中获取ObjectInputStream

Serializable classes that require special handling during the serialization and deserialization process should implement the following methods: 在序列化和反序列化过程中需要特殊处理的可序列化类应实现以下方法:

private void writeObject(java.io.ObjectOutputStream stream) throws IOException;
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException;
private void readObjectNoData() throws ObjectStreamException;

So you could read in data manually using stream.read(...) inside your custom readObject method and use that to set member variables on your object. 因此,您可以使用自定义readObject方法中的stream.read(...)手动读取数据,并使用它在对象上设置成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM