1 16 package org.apache.commons.lang; 17 18 import java.io.ByteArrayInputStream ; 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.io.ObjectInputStream ; 23 import java.io.ObjectOutputStream ; 24 import java.io.OutputStream ; 25 import java.io.Serializable ; 26 27 49 public class SerializationUtils { 50 51 59 public SerializationUtils() { 60 super(); 61 } 62 63 78 public static Object clone(Serializable object) { 79 return deserialize(serialize(object)); 80 } 81 82 99 public static void serialize(Serializable obj, OutputStream outputStream) { 100 if (outputStream == null) { 101 throw new IllegalArgumentException ("The OutputStream must not be null"); 102 } 103 ObjectOutputStream out = null; 104 try { 105 out = new ObjectOutputStream (outputStream); 107 out.writeObject(obj); 108 109 } catch (IOException ex) { 110 throw new SerializationException(ex); 111 } finally { 112 try { 113 if (out != null) { 114 out.close(); 115 } 116 } catch (IOException ex) { 117 } 119 } 120 } 121 122 130 public static byte[] serialize(Serializable obj) { 131 ByteArrayOutputStream baos = new ByteArrayOutputStream (512); 132 serialize(obj, baos); 133 return baos.toByteArray(); 134 } 135 136 153 public static Object deserialize(InputStream inputStream) { 154 if (inputStream == null) { 155 throw new IllegalArgumentException ("The InputStream must not be null"); 156 } 157 ObjectInputStream in = null; 158 try { 159 in = new ObjectInputStream (inputStream); 161 return in.readObject(); 162 163 } catch (ClassNotFoundException ex) { 164 throw new SerializationException(ex); 165 } catch (IOException ex) { 166 throw new SerializationException(ex); 167 } finally { 168 try { 169 if (in != null) { 170 in.close(); 171 } 172 } catch (IOException ex) { 173 } 175 } 176 } 177 178 186 public static Object deserialize(byte[] objectData) { 187 if (objectData == null) { 188 throw new IllegalArgumentException ("The byte[] must not be null"); 189 } 190 ByteArrayInputStream bais = new ByteArrayInputStream (objectData); 191 return deserialize(bais); 192 } 193 194 } 195 | Popular Tags |