//加了了Optional防止空指针异常,加入了泛型,省去了强制转化
1 import java.io.*; 2 import java.util.Optional; 3 4 /** 5 * Created by Jason on 2017/1/3. 6 */ 7 public class ByteArrayUtils { 8 9 public static<T> Optional<byte[]> objectToBytes(T obj){ 10 byte[] bytes = null; 11 ByteArrayOutputStream out = new ByteArrayOutputStream(); 12 ObjectOutputStream sOut; 13 try { 14 sOut = new ObjectOutputStream(out); 15 sOut.writeObject(obj); 16 sOut.flush(); 17 bytes= out.toByteArray(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 return Optional.ofNullable(bytes); 22 } 23 24 public static<T> Optional<T> bytesToObject(byte[] bytes) { 25 T t = null; 26 ByteArrayInputStream in = new ByteArrayInputStream(bytes); 27 ObjectInputStream sIn; 28 try { 29 sIn = new ObjectInputStream(in); 30 t = (T)sIn.readObject(); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 return Optional.ofNullable(t); 35 36 } 37 } 38 --------------------- 39 作者:idealemail 40 来源:CSDN 41 原文:https://blog.csdn.net/idealemail/article/details/53993872 42 版权声明:本文为博主原创文章,转载请附上博文链接!