Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting byte[] to user defined class in java

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?

like image 218
JGC Avatar asked Aug 05 '26 11:08

JGC


2 Answers

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.

like image 54
Yannick Motton Avatar answered Aug 07 '26 00:08

Yannick Motton


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).

like image 33
Michael Borgwardt Avatar answered Aug 06 '26 23:08

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!