Java Serialize serializeClone(final Object obj)

Here you can find the source of serializeClone(final Object obj)

Description

Creates a clone by serializing object and deserializing byte stream.

License

Apache License

Parameter

Parameter Description
obj object to serialize and deserialize.

Exception

Parameter Description
IOException on IO error.
ClassNotFoundException if class not found.

Return

clone

Declaration

public static Object serializeClone(final Object obj)
        throws IOException, ClassNotFoundException 

Method Source Code

//package com.java2s;
/*//from  w  w w. j a  v  a  2s  . com
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
    /**
     * Creates a clone by serializing object and
     * deserializing byte stream.
     * @param obj object to serialize and deserialize.
     * @return clone
     * @throws IOException on IO error.
     * @throws ClassNotFoundException if class not found.
     */
    public static Object serializeClone(final Object obj)
            throws IOException, ClassNotFoundException {
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        ObjectOutputStream objOut = new ObjectOutputStream(memOut);
        objOut.writeObject(obj);
        objOut.close();

        ByteArrayInputStream src = new ByteArrayInputStream(
                memOut.toByteArray());
        ObjectInputStream objIs = new ObjectInputStream(src);

        return objIs.readObject();
    }
}

Related

  1. serializeCookie(Object object, String filePath)
  2. serializedCopy(Object obj)
  3. serializedCopy(T object)
  4. serializeDistributionType(String distributionType, String HadoopDistribution)