Java Object to ByteBuffer serialize(Object obj)

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

Description

serialize

License

Apache License

Declaration

public static byte[] serialize(Object obj) 

Method Source Code

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

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

import java.io.ObjectOutputStream;

import java.nio.ByteBuffer;

import java.util.Map;

public class Main {
    public static byte[] serialize(Object obj) {
        try {//  w  w  w.  j a  v  a 2 s  . c  om
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.close();
            return bos.toByteArray();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    public static byte[] toByteArray(ByteBuffer buffer) {
        byte[] ret = new byte[buffer.remaining()];
        buffer.get(ret, 0, ret.length);
        return ret;
    }

    public static <S, T> T get(Map<S, T> m, S key, T def) {
        T ret = m.get(key);
        if (ret == null) {
            ret = def;
        }
        return ret;
    }
}

Related

  1. serialize(Object msg)
  2. serialize(Object obj)
  3. serialize(Object state)
  4. serialize(Object value)