Java Object to ByteBuffer serialize(Object value)

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

Description

serialize

License

Apache License

Declaration

public static byte[] serialize(Object value) 

Method Source Code


//package com.java2s;
/*//from  w  ww  .j ava 2 s  . c  om
 * #%L
 * rapidoid-commons
 * %%
 * Copyright (C) 2014 - 2016 Nikolche Mihajlovski and contributors
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.io.*;

import java.nio.ByteBuffer;

public class Main {
    public static byte[] serialize(Object value) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(output);
            out.writeObject(value);
            output.close();

            return output.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void serialize(Object value, ByteBuffer buf) {
        byte[] bytes = serialize(value);
        buf.putInt(bytes.length);
        buf.put(bytes);
    }
}

Related

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