Here you can find the source of deepClone(final T objectToBeClonned)
Parameter | Description |
---|---|
objectToBeClonned | from which a new object will be cloned. null will be returned for null value. |
Parameter | Description |
---|---|
CloneNotSupportedException | an exception |
@SuppressWarnings("unchecked") public static <T> T deepClone(final T objectToBeClonned) throws CloneNotSupportedException
//package com.java2s; /*/*from w w w .j a v a 2 s. com*/ * Copyright 2014-2016 Web Firm Framework * * 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. * @author WFF */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Main { /** * @param objectToBeClonned * from which a new object will be cloned. {@code null} will be * returned for null value. * @return the newly cloned object or {@cod null} if * {@code objectToBeClonned} is null. * @throws CloneNotSupportedException * @since 1.0.0 * @author WFF */ @SuppressWarnings("unchecked") public static <T> T deepClone(final T objectToBeClonned) throws CloneNotSupportedException { if (objectToBeClonned == null) { return null; } ObjectOutputStream oos = null; ObjectInputStream ois = null; try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(objectToBeClonned); oos.flush(); final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); return (T) ois.readObject(); } catch (final NotSerializableException e) { throw new CloneNotSupportedException( e.getMessage() + " is not serializable. Implement java.io.Serializable in " + e.getMessage()); } catch (final Exception e) { throw new CloneNotSupportedException(e.getMessage()); } finally { try { if (oos != null) { oos.close(); } if (ois != null) { ois.close(); } } catch (final IOException e) { e.printStackTrace(); } } } }