View Javadoc
1   /*
2    *    Copyright 2009-2021 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.submitted.serializecircular;
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  
24  public class UtilityTester {
25  
26    public static void serializeAndDeserializeObject(Object myObject) {
27  
28      try {
29        deserialzeObject(serializeObject(myObject));
30      } catch (IOException e) {
31        System.out.println("Exception: " + e.toString());
32      }
33    }
34  
35    private static byte[] serializeObject(Object myObject) throws IOException {
36      try {
37        ByteArrayOutputStream myByteArrayOutputStream = new ByteArrayOutputStream();
38  
39        // Serialize to a byte array
40        try (ObjectOutputStream myObjectOutputStream = new ObjectOutputStream(myByteArrayOutputStream)) {
41          myObjectOutputStream.writeObject(myObject);
42        }
43  
44        // Get the bytes of the serialized object
45        byte[] myResult = myByteArrayOutputStream.toByteArray();
46        return myResult;
47      } catch (Exception anException) {
48        throw new RuntimeException("Problem serializing: " + anException.toString(), anException);
49      }
50    }
51  
52    private static Object deserialzeObject(byte[] aSerializedObject) {
53      // Deserialize from a byte array
54      try (ObjectInputStream myObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(aSerializedObject))) {
55        return myObjectInputStream.readObject();
56      } catch (Exception anException) {
57        throw new RuntimeException("Problem deserializing", anException);
58      }
59    }
60  
61  }