I get in my function message array of bytes and type of object, I need to restore object from bytes. Is there in Java any cast like in C++ ?
here are the methods to accomplish what you want.
public static Object toObjectFromByteArray(byte[] byteArr) {
if (byteArr == null) {
return null;
}
Object resultObj = null;
ByteArrayInputStream bin = null;
ObjectInputStream ooin = null;
try {
bin = new ByteArrayInputStream(byteArr);
ooin = new ObjectInputStream(bin);
resultObj = ooin.readObject();
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
finally {
try {
if (ooin != null) {
ooin.close();
}
if (bin != null) {
bin.close();
}
}
catch (IOException ex1) {
ex1.printStackTrace();
}
}
return resultObj;
}
public static byte[] toByteArray(Object obj) {
ByteArrayOutputStream barr = null;
ObjectOutputStream oout = null;
byte[] bytearr = null;
try {
byte[] b2 = null;
barr = new ByteArrayOutputStream(10000);
oout = new ObjectOutputStream(barr);
oout.writeObject(obj);
oout.flush();
oout.close();
bytearr = barr.toByteArray();
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
finally {
try {
if (oout != null) {
oout.close();
}
if (barr != null) {
barr.close();
}
}
catch (IOException ex1) {
ex1.printStackTrace();
}
}
return bytearr;
}