Java Object Serialize serialize(T obj)

Here you can find the source of serialize(T obj)

Description

serialize

License

Open Source License

Declaration

public static <T extends Serializable> byte[] serialize(T obj) 

Method Source Code


//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 */ }
            }
        }
    }
}

Related

  1. serialize(Serializable s, File dir, String fileName)
  2. serialize(Serializable serializable)
  3. serialize(Serializable... objects)
  4. serialize(String filename, T obj)
  5. serialize(String path, String name, Object obj)
  6. serialize(T obj)
  7. serialize(T object)
  8. serialize(T object)
  9. serialize(T object)