Created
July 8, 2012 21:59
-
-
Save alessandroleite/3073090 to your computer and use it in GitHub Desktop.
Classe Utilitária para serialização e desserialização de Objectos Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.Closeable; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
import org.apache.commons.logging.Log; | |
import org.apache.commons.logging.LogFactory; | |
public final class Objects { | |
private final static Log LOG = LogFactory.getLog(Objects.class.getName()); | |
public static final byte[] serialize(Serializable obj) { | |
if (obj == null) | |
return new byte[0]; | |
ByteArrayOutputStream baos = null; | |
ObjectOutputStream oos = null; | |
try { | |
oos = new ObjectOutputStream(baos = new ByteArrayOutputStream()); | |
oos.writeObject(obj); | |
return baos.toByteArray(); | |
} catch (IOException exception) { | |
throw new RuntimeException(exception); | |
} finally { | |
closeQuiently(new Closeable[] { baos, oos }); | |
} | |
} | |
public static Object desserialize(byte[] b) throws ClassNotFoundException { | |
if (b == null || b.length == 0) | |
return null; | |
ByteArrayInputStream bais = null; | |
ObjectInputStream ois = null; | |
try { | |
ois = new ObjectInputStream(bais = new ByteArrayInputStream(b)); | |
return ois.readObject(); | |
} catch (IOException exception) { | |
throw new RuntimeException(exception); | |
} finally { | |
closeQuiently(new Closeable[] { bais, ois }); | |
} | |
} | |
private static void closeQuiently(Closeable res) { | |
if (res != null) | |
try { | |
res.close(); | |
} catch (IOException ignore) { | |
LOG.error("Erro ao liberar recurso! Causa:" | |
+ ignore.getMessage()); | |
} | |
} | |
private static void closeQuiently(Closeable[] resources) { | |
if (resources != null) { | |
for (int i = 0; i < resources.length; i++) { | |
closeQuiently(resources[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment