View Javadoc
1   /*
2    *    Copyright 2009-2023 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    *       https://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        return myByteArrayOutputStream.toByteArray();
45      } catch (Exception anException) {
46        throw new RuntimeException("Problem serializing: " + anException.toString(), anException);
47      }
48    }
49  
50    private static Object deserialzeObject(byte[] aSerializedObject) {
51      // Deserialize from a byte array
52      try (ObjectInputStream myObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(aSerializedObject))) {
53        return myObjectInputStream.readObject();
54      } catch (Exception anException) {
55        throw new RuntimeException("Problem deserializing", anException);
56      }
57    }
58  
59    private UtilityTester() {
60    }
61  
62  }