我有一个包含两个类对象和一些变量的类。我想通过带有发送功能的 USB 发送一个类的实例(并在另一边接收)。send 函数接受字节数组 (byte[])。
我的问题是如何将类的实例转换为字节数组以便我可以发送它?我如何在另一边正确重建它?
下面是我要发送和接收的类 Comsstruct。欢迎任何建议!
// ObjectInfo struct definition
public class ObjectInfo {
int ObjectXCor;
int ObjectYCor;
int ObjectMass;
};
// ObjectInfo struct definition
public class SensorDataStruct{
int PingData;
int IRData;
int ForceData;
int CompassData;
};
// ObjectInfo struct definition
public class CommStruct{
public ObjectInfo VisionData;
public SensorDataStruct SensorData;
};
public CommStruct SendPacket;
public CommStruct RecievePacket;
更新
我找到了一个解决方案,但是根据我得到的建议,我想知道这是否可行(以及它是否是一个好的解决方案)?
有一个序列化方法和一个发送方法:
// Method to convert object to a byte array
public static byte[] serializeObject(CommStruct obj) throws IOException
{
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
oos.writeObject(obj);
oos.flush();
byte[] bytes = bytesOut.toByteArray();
bytesOut.close();
oos.close();
return bytes;
}
// Send struct function
public void Send(){
try
{
// First convert the CommStruct to a byte array
// Then send the byte array
server.send(serializeObject(SendPacket));
}
catch (IOException e)
{
Log.e("microbridge", "problem sending TCP message", e);
}
和一个接收处理函数:
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{
// Event handler for recieving data
// Try to receive CommStruct
try
{
ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bytesIn);
RecievePacket = (CommStruct) ois.readObject();
ois.close();
}
catch (IOException e)
{
Log.e("microbridge", "problem recieving TCP message", e);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("microbridge", "problem recieving TCP message", e);
}
// Send the recieved data packet back
SendPacket = RecievePacket;
// Send CommStruct
Send();
}
我的问题是这是否是一个好的解决方案?