Java Object Serialize serialize(Object obj)

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

Description

Serializes an object into a byte array.

License

Apache License

Parameter

Parameter Description
obj the object to serialize

Exception

Parameter Description
IOException if the serialization fails

Return

the serialized bytes

Declaration

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

Method Source Code

//package com.java2s;
/*//from   w  w w .  j a  va2  s  .com
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

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

import java.io.ObjectOutputStream;

public class Main {
    /**
     * Serializes an object into a byte array. When the object is null, returns null.
     *
     * @param obj the object to serialize
     * @return the serialized bytes
     * @throws IOException if the serialization fails
     */
    public static byte[] serialize(Object obj) throws IOException {
        if (obj == null) {
            return null;
        }
        try (ByteArrayOutputStream b = new ByteArrayOutputStream()) {
            try (ObjectOutputStream o = new ObjectOutputStream(b)) {
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    /**
     * Wrapper around {@link #serialize(Object)} which throws a runtime exception with the given
     * message on failure.
     *
     * @param obj the object the serialize
     * @param errorMessage the message to show if serialization fails
     * @return the serialized bytes
     */
    public static byte[] serialize(Object obj, String errorMessage) {
        try {
            return serialize(obj);
        } catch (IOException e) {
            throw new RuntimeException(errorMessage, e);
        }
    }
}

Related

  1. serialize(Object obj)
  2. serialize(Object obj)
  3. serialize(Object obj)
  4. serialize(Object obj)
  5. serialize(Object obj)
  6. serialize(Object obj)
  7. serialize(Object obj)
  8. serialize(Object obj, String file)
  9. serialize(Object obj, String fileName)