Java Serialize serializeJdk(Object obj)

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

Description

Serializes a given object into byte array.

License

Open Source License

Parameter

Parameter Description
obj Object to serialize.

Exception

Parameter Description
IOException If serialization failed.

Return

Byte array containing serialized object.

Declaration

public static byte[] serializeJdk(Object obj) throws IOException 

Method Source Code


//package com.java2s;
/* //w  ww  .  java 2  s .c o  m
 Copyright (C) GridGain Systems. All Rights Reserved.
     
 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.
 */

import java.io.*;

public class Main {
    /**
     * Serializes a given object into byte array.
     *
     * @param obj Object to serialize.
     * @return Byte array containing serialized object.
     * @throws IOException If serialization failed.
     */
    public static byte[] serializeJdk(Object obj) throws IOException {
        ByteArrayOutputStream byteOut = null;

        ObjectOutputStream objOut = null;

        try {
            // Allocate half of kilobyte to avoid very small resizings.
            byteOut = new ByteArrayOutputStream(512);

            objOut = new ObjectOutputStream(byteOut);

            // Make sure that we serialize only task, without
            // class loader.
            objOut.writeObject(obj);

            objOut.flush();

            return byteOut.toByteArray();
        } finally {
            close(objOut);
            close(byteOut);
        }
    }

    /**
     * Closes resource.
     *
     * @param c Resource
     * @throws IOException If failed to close resource.
     */
    private static void close(Closeable c) throws IOException {
        if (c != null)
            c.close();
    }
}

Related

  1. serializeGZip(T obj)
  2. serializeInt(int i)
  3. serializeInt2MinLE(int value)
  4. serializeInt2MinLE(int value)
  5. serializeIntLE(int value, byte[] outbuf, int offset)
  6. serializeMock(Object mock)
  7. serializeObject(B b)
  8. serializeObject(final Object object)
  9. serializeObject(String absFilePath, Object obj)