Java Object Serialize serialize(@Nonnull T object)

Here you can find the source of serialize(@Nonnull T object)

Description

Serialize an object.

License

Open Source License

Parameter

Parameter Description
object The object to serialize.

Return

A serialized byte array of the object.

Declaration

@Nonnull
public static <T extends Serializable> byte[] serialize(@Nonnull T object) throws IOException 

Method Source Code


//package com.java2s;
/*//from w  w  w. jav  a 2  s  .  com
 * This file is part of LaS-VPE Platform.
 *
 * LaS-VPE Platform is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LaS-VPE Platform is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LaS-VPE Platform.  If not, see <http://www.gnu.org/licenses/>.
 */

import javax.annotation.Nonnull;
import java.io.*;

public class Main {
    /**
     * Serialize an object.
     *
     * @param object The object to serialize.
     * @return A serialized byte array of the object.
     */
    @Nonnull
    public static <T extends Serializable> byte[] serialize(@Nonnull T object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutput objectOutput = null;
        try {
            objectOutput = new ObjectOutputStream(byteArrayOutputStream);
            objectOutput.writeObject(object);
            return byteArrayOutputStream.toByteArray();
        } finally {
            try {
                if (objectOutput != null) {
                    objectOutput.close();
                }
            } catch (IOException e) {
                // ignore close exception
            }
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                // ignore close exception
            }
        }
    }
}

Related

  1. serialize(@Nullable final Object obj)
  2. serialize(@Nullable Object value)
  3. serialize(File outFile, Object source)
  4. serialize(final @Nonnull Object obj)