Java Object to ByteBuffer serialize(Object obj)

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

Description

Serialize an object into a ByteBuffer.

License

Apache License

Parameter

Parameter Description
obj Object to serialize

Return

Buffer of the serialized object

Declaration

public static ByteBuffer 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;

public class Main {
    /**// ww w . jav a2 s. c o m
     * Serialize an object into a ByteBuffer.
     * @param obj Object to serialize
     * @return Buffer of the serialized object
     */
    public static ByteBuffer serialize(Object obj) {
        try {
            //todo: make serialization less clunky!
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            byte[] b = baos.toByteArray();
            oos.close();
            return ByteBuffer.wrap(b);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

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