001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
019 import com.liferay.portal.kernel.util.ClassLoaderObjectInputStream;
020 import com.liferay.portal.kernel.util.StreamUtil;
021
022 import java.io.IOException;
023 import java.io.ObjectInputStream;
024 import java.io.ObjectOutputStream;
025
026
030 public class SerializableUtil {
031
032 public static Object clone(Object object) {
033 return deserialize(serialize(object));
034 }
035
036 public static Object deserialize(byte[] bytes) {
037 ObjectInputStream objectInputStream = null;
038
039 try {
040 objectInputStream = new ObjectInputStream(
041 new UnsyncByteArrayInputStream(bytes));
042
043 return objectInputStream.readObject();
044 }
045 catch (ClassNotFoundException cnfe) {
046 throw new RuntimeException(cnfe);
047 }
048 catch (IOException ioe) {
049 throw new RuntimeException(ioe);
050 }
051 finally {
052 StreamUtil.cleanUp(objectInputStream);
053 }
054 }
055
056 public static Object deserialize(byte[] bytes, ClassLoader classLoader) {
057 ObjectInputStream objectInputStream = null;
058
059 try {
060 objectInputStream = new ClassLoaderObjectInputStream(
061 new UnsyncByteArrayInputStream(bytes), classLoader);
062
063 return objectInputStream.readObject();
064 }
065 catch (ClassNotFoundException cnfe) {
066 throw new RuntimeException(cnfe);
067 }
068 catch (IOException ioe) {
069 throw new RuntimeException(ioe);
070 }
071 finally {
072 StreamUtil.cleanUp(objectInputStream);
073 }
074 }
075
076 public static byte[] serialize(Object object) {
077 ObjectOutputStream objectOutputStream = null;
078
079 UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
080 new UnsyncByteArrayOutputStream();
081
082 try {
083 objectOutputStream = new ObjectOutputStream(
084 unsyncByteArrayOutputStream);
085
086 objectOutputStream.writeObject(object);
087 }
088 catch (IOException ioe) {
089 throw new RuntimeException(ioe);
090 }
091 finally {
092 StreamUtil.cleanUp(objectOutputStream);
093 }
094
095 return unsyncByteArrayOutputStream.toByteArray();
096 }
097
098 }