gpt4 book ai didi

java - 将字节数组分配给 Java 对象

转载 作者:行者123 更新时间:2023-12-02 02:52:49 25 4
gpt4 key购买 nike

是否可以将字节数组(通过 tcp 套接字接收)直接分配给 Java 对象而不解析数据?

在c中可以直接将字节分配给结构体,在java中可以吗?

最佳答案

不可能将字节数组分配给java中的对象并自动填充所有成员变量,但可以使用序列化从字节数组中获取java对象。

您可以使用ObjectInputStreamObjectOutputStream从流中获取对象。要从字节数组中获取一个,请将 ByteArrayInputStream 包装在 ObjectInputStream 中。该对象必须实现 Serialized 接口(interface)。这应该可以帮助您避免手动解析字节数组。

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

如果您正在读取的数据不是序列化的 java 对象,您可以向该对象添加方法来帮助序列化。

来自 ObjectInputStream 的 javadoc

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;

因此,您可以在自定义 readObject 方法中使用stream.read(...) 手动读取数据,并使用它来设置对象上的成员变量。

关于java - 将字节数组分配给 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com