Java Object to Byte Array getBytes(Object o)

Here you can find the source of getBytes(Object o)

Description

get Bytes

License

Apache License

Declaration

public static byte[] getBytes(Object o) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static byte[] getBytes(Object o) {
        if (o instanceof String) {
            return ((String) o).getBytes();
        } else if (o instanceof byte[]) {
            return ((byte[]) o);
        } else if (o instanceof Serializable) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = null;
            try {
                out = new ObjectOutputStream(bos);
                out.writeObject(o);//from   w w  w .ja v a2  s .  c  o m
                return bos.toByteArray();
            } catch (Exception e) {
                return null;
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {/**/
                }

                try {
                    bos.close();
                } catch (IOException e) {/**/
                }
            }
        }

        throw new RuntimeException("Fail to convert object to bytes");
    }
}

Related

  1. getBytes(Object o)
  2. getBytes(Object o)
  3. getBytes(Object obj)
  4. getBytes(Object obj)