【转载】java对象和byte数组互转,直接拿去⽤//加了了Optional防⽌空指针异常,加⼊了泛型,省去了强制转化
1import java.io.*;
2import java.util.Optional;
3
4/**
5 * Created by Jason on 2017/1/3.
6*/
7public class ByteArrayUtils {
8
9public static<T> Optional<byte[]> objectToBytes(T obj){
10byte[] bytes = null;
11 ByteArrayOutputStream out = new ByteArrayOutputStream();
12 ObjectOutputStream sOut;
13try {
14 sOut = new ObjectOutputStream(out);
15 sOut.writeObject(obj);
16 sOut.flush();
17 bytes= ByteArray();
18 } catch (IOException e) {
19 e.printStackTrace();
20 }
21return Optional.ofNullable(bytes);
22 }
23
24public static<T> Optional<T> bytesToObject(byte[] bytes) {
25 T t = null;
26 ByteArrayInputStream in = new ByteArrayInputStream(bytes);
27 ObjectInputStream sIn;
28try {
29 sIn = new ObjectInputStream(in);
30 t = (adObject();
31 } catch (Exception e) {
object to32 e.printStackTrace();
33 }
34return Optional.ofNullable(t);
35
36 }
37 }
38 ---------------------
39作者:idealemail
40来源:CSDN
41原⽂:blog.csdn/idealemail/article/details/53993872
42版权声明:本⽂为博主原创⽂章,转载请附上博⽂链接!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论