1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.batch.support;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectInputStream;
22 import java.io.ObjectOutputStream;
23 import java.io.OptionalDataException;
24
25
26
27
28
29
30
31
32 public class SerializationUtils {
33
34
35
36
37
38
39
40 public static byte[] serialize(Object object) {
41
42 if (object==null) {
43 return null;
44 }
45
46 ByteArrayOutputStream stream = new ByteArrayOutputStream();
47 try {
48 new ObjectOutputStream(stream).writeObject(object);
49 } catch (IOException e) {
50 throw new IllegalArgumentException("Could not serialize object of type: "+object.getClass(), e);
51 }
52
53 return stream.toByteArray();
54
55 }
56
57
58
59
60
61 public static Object deserialize(byte[] bytes) {
62
63 if (bytes==null) {
64 return null;
65 }
66
67 try {
68 return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
69 }
70 catch (OptionalDataException e) {
71 throw new IllegalArgumentException("Could not deserialize object: eof="+e.eof+ " at length="+e.length, e);
72 }
73 catch (IOException e) {
74 throw new IllegalArgumentException("Could not deserialize object", e);
75 }
76 catch (ClassNotFoundException e) {
77 throw new IllegalStateException("Could not deserialize object type", e);
78 }
79
80 }
81
82 }