i want to cast byte[] which i got from socket a class which I write it (Message). I tried
byte[] data=new btyte[100];
.
.
.
Message m=(Message)data;
but it did not work and give me error what should I do?
Assuming you are talking about a serialized object:
try this:
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
Message message = (Message) in.readObject();
in.close();
In case you are serializing the Message in some other way, you will have to parse it yourself, using a parametrized constructor or a static method that returns a new instance of the type.
You cannot cast arbitrary binary data (in Java).
What's that byte[] supposed to contain? If it's a serialized instance of the class, you'll have to wrap the socket's InputStream in an ObjectInputStream. If it's aother well-defined binary format, you'll have to parse it manually (Note: dumping C structs does not constitute a well-defined binary format and should be avoided).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With