1 23 24 package com.rift.coad.lib.common; 26 27 import java.io.IOException ; 29 import java.io.InputStream ; 30 import java.io.ByteArrayInputStream ; 31 import java.io.ByteArrayOutputStream ; 32 import java.io.ObjectInputStream ; 33 import java.io.ObjectOutputStream ; 34 import java.io.ObjectStreamClass ; 35 36 41 public class ObjectSerializer { 42 43 47 public static class ClassLoaderObjectInputStream extends ObjectInputStream { 48 53 public ClassLoaderObjectInputStream() throws IOException { 54 super(); 55 } 56 57 58 64 public ClassLoaderObjectInputStream(InputStream in) throws IOException { 65 super(in); 66 } 67 68 69 77 protected Class resolveClass(ObjectStreamClass desc) throws IOException , 78 ClassNotFoundException { 79 return Thread.currentThread().getContextClassLoader().loadClass( 80 desc.getName()); 81 } 82 83 } 84 85 88 private ObjectSerializer() { 89 } 90 91 92 99 public static byte[] serialize(Object ref) throws CommonException { 100 try { 101 if (!(ref instanceof java.io.Serializable )) { 102 throw new CommonException("This object is not serializable. " + 103 "Must implement from java.io.Serializable."); 104 } 105 ByteArrayOutputStream byteOutput = new ByteArrayOutputStream (); 106 ObjectOutputStream objOutput = new ObjectOutputStream (byteOutput); 107 objOutput.writeObject(ref); 108 objOutput.flush(); 109 objOutput.close(); 110 return byteOutput.toByteArray(); 111 } catch (CommonException ex) { 112 throw ex; 113 } catch (Exception ex) { 114 throw new CommonException("Failed to serialize the object : " + 115 ex.getMessage(),ex); 116 } 117 } 118 119 120 127 public static Object deserialize(byte[] input) throws CommonException { 128 try { 129 ByteArrayInputStream byteInput = new ByteArrayInputStream (input); 130 ClassLoaderObjectInputStream objInput = 131 new ClassLoaderObjectInputStream(byteInput); 132 Object ref = objInput.readObject(); 133 objInput.close(); 134 return ref; 135 } catch (Exception ex) { 136 throw new CommonException("Failed to deserialize the object : " + 137 ex.getMessage(),ex); 138 } 139 } 140 } 141 | Popular Tags |