Is there cast in Java similar to in C++

后端 未结 7 1031
小蘑菇
小蘑菇 2020-12-04 01:54

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++ ?

7条回答
  •  感动是毒
    2020-12-04 02:45

    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;
        }
    

提交回复
热议问题