Java Object to Byte Array getBytes(Object obj)

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

Description

get Bytes

License

Open Source License

Declaration

public static byte[] getBytes(Object obj) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Main {
    public static byte[] getBytes(Object obj) {
        if (obj instanceof byte[])
            return (byte[]) obj;

        if (obj instanceof String)
            return ((String) obj).getBytes();

        try {//  ww w . j  a  v a 2s.  c  om
            return serialize(obj);
        } catch (Exception ex) {
        }

        return new byte[] {};
    }

    public static byte[] serialize(Object obj) throws IOException {
        try (ByteArrayOutputStream b = new ByteArrayOutputStream()) {
            try (ObjectOutputStream o = new ObjectOutputStream(b)) {
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }
}

Related

  1. getBytes(Object o)
  2. getBytes(Object o)
  3. getBytes(Object o)
  4. getBytes(Object obj)
  5. getBytes(Object obj)
  6. getBytes(Object obj)
  7. getBytes(Object obj)
  8. getBytes(Object obj)
  9. getBytes(Object v, byte[] defaultValue)