This class provides methods for serializing and deserializing objects, which are often used in actual projects.
1 ImportJava.io.*;2 3 Public classSerializationutils {4 5 //serialization of an object6 Public Static byte[] Serialize (Object state) {7ObjectOutputStream Oos =NULL;8 Try {9Bytearrayoutputstream BOS =NewBytearrayoutputstream (512);TenOos =NewObjectOutputStream (BOS); One Oos.writeobject (state); A Oos.flush (); - returnBos.tobytearray (); - } the Catch(IOException e) { - Throw NewIllegalArgumentException (e); - } - finally { + if(Oos! =NULL) { - Try { + oos.close (); A } at Catch(IOException e) { - //Eat It - } - } - } - } in - //to deserialize an object to Public Static<T> T Deserialize (byte[] byteArray) { +ObjectInputStream OIP =NULL; - Try { theOIP =NewObjectInputStream (NewBytearrayinputstream (ByteArray)); *@SuppressWarnings ("Unchecked") $T result =(T) oip.readobject ();Panax Notoginseng returnresult; - } the Catch(IOException e) { + Throw NewIllegalArgumentException (e); A } the Catch(ClassNotFoundException e) { + Throw NewIllegalArgumentException (e); - } $ finally { $ if(OIP! =NULL) { - Try { - oip.close (); the } - Catch(IOException e) {Wuyi //Eat It the } - } Wu } - } About $}
Object Serialization Tool Class