Here you can find the source of serialize(T obj)
public static <T extends Serializable> byte[] serialize(T obj)
//package com.java2s; //License from project: Open Source License import java.io.*; public class Main { public static <T extends Serializable> byte[] serialize(T obj) { try {/*from w w w.ja v a2 s.c o m*/ ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(baos); out.writeObject(obj); out.flush(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { /* NOP */ } } } baos.flush(); return baos.toByteArray(); } finally { if (baos != null) { try { baos.close(); } catch (Exception e) { /* NOP */ } } } } catch (Exception e) { throw new RuntimeException(e); } } public static <T extends Externalizable> byte[] serialize(T obj) { try { return serializeSafe(obj); } catch (Exception e) { throw new RuntimeException(e); } } public static <T extends Externalizable> byte[] serializeSafe(T obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(baos); obj.writeExternal(out); out.flush(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { /* NOP */ } } } baos.flush(); return baos.toByteArray(); } finally { if (baos != null) { try { baos.close(); } catch (Exception e) { /* NOP */ } } } } }