Converting a byte stream to an Object
I have a Packet class (com.lab.tracking.Packet) in an Android project. I need to send this packet via UDP to a Server, that has an exactly copy of that Packet class (com.server.serverTracking.Packet).
The android app converts the Packet into a byte stream, and then it sends it to the server. The server receives the byte stream correctly, but when it tries to convert it to a Packet, it throws an exception:
java.lang.ClassNotFoundException: com.lab.tracking.Packet
I understand that. The server is trying to convert this object to a com.lab.tracking.Packet, instead of a c开发者_StackOverflow中文版om.server.serverTracking.Packet).
The conversion from byte stream to Object is:
public static Object toObject(byte[] dataReceived) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(dataReceived);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
How could I avoid this? Both classes are exactly the same, so I think the problem is in the complete name (or ID, or whatever).
Thanks!
To expand on djg's answer, the problem is that your Packet classes are not "exactly the same" because they are in different packages.
So the solution would be to get rid of com.server.serverTracking.Packet
and move com.lab.tracking.Packet
to a common library that both the android app and the server side code depend on.
That being said, I would recommend against using Java object serialization between and android app and the server. If your Packet
changes in any significant way (new member variables, etc.) with new releases, you will likely break all previous versions. At the very least, you should explicitly specify a serialVersionUid.
A better solution would be to design a structure for the packet byte array, and use a factory class or constructor that parses the byte array into a Java object.
Put the packet implementation in a core library that both the android project and server depend on.
精彩评论