开发者

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)dat开发者_StackOverflowa;

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


You're probably better off writing a function to do it.

Message parseDataFromSocket(byte[] bytes);


You need to create a Message constructor that takes a byte[] (and uses it to somehow initialise the object). You can then do:

Message m = new Message(data);


If the byte array was serialized normally, you can use a ByteArrayInputStream, pass that into an ObjectInputStream and cast the resulting Object into your Message class.


It depends on how the byte array was created... You could try:

ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))
Message m = (Message) in.readObject();


Try using an ObjectInputStream with a ByteArrayInputStream.

It looks like your trying to read a serialized class.

Edited to ByteArrayInputStream as mention above.


In Java it is not possible to perform such casts (in C++, for example, one can define conversion constructors and the likes).

You've tagged the question with 'serialization'. Assuming you are using the Java serialization API, then as you were already directed, you should feed the data array through an ObjectInputStream in order for it to deserialize the array into an object. More information can be found here.

Furthermore, in case you've used some other sort of serialization (for example, using XStream to serialize to XML) then you should deserialize (unmarshalling is another common name for this) the data using the same API that was used to serialize it in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜