Skip to content

Instantly share code, notes, and snippets.

@alessandroleite
Created July 8, 2012 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alessandroleite/3073090 to your computer and use it in GitHub Desktop.
Save alessandroleite/3073090 to your computer and use it in GitHub Desktop.
Classe Utilitária para serialização e desserialização de Objectos Java
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