c#和java的深拷贝CloneObject

 public static T Clone<T>(this T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            // Don't serialize a null object, simply return the default for that object
            if (Object.ReferenceEquals(source, null))
            {
                return default(T);
            }

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }

 

java 代码

class DeepClone
{
    public static <T extends Serializable> T clone(T obj)
    {
        try {
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

            ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);

            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);

            return (T)objectInputStream.readObject();
        }
        catch (Exception ex){

        }
        return null;
    }
}

 

posted @ 2017-05-31 15:52  zslm___  阅读(265)  评论(0编辑  收藏  举报