【Java】对象的拷贝

几个概念

浅拷贝

基本数据类型拷贝数值,而对象拷贝对象的引用。

深拷贝

基本数据类型拷贝数值,而对象,则创建一个新的对象,并把原本对象里面的值一一拷贝到新的对象中,开辟了新的内存空间,而不仅仅引用同一个对象。

native

JNI是Java Native Interface的 缩写。从Java 1.1开始,Java Native Interface (JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他语言,只要调用约定受支持就可以了。使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的,比如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少保证本地代码能工作在任何Java 虚拟机实现下。

Object的clone方法

自定义类实现clone方法的要求
  • 继承Object
    因为Java中除了极个别的类之外,都是继承自Object,所以都从Object中继承了clone方法。
  • 实现Cloneable接口
    Cloneable并没有声明的方法,所以这个接口相当于一个“标记”的作用,标记该类可以调用clone方法。如果某些类不需要实现clone,就可以不实现该接口,从而达到一个保护的作用。如果没有实现该接口,而去调用clone方法的话则会抛出CloneNotSupportedException
  • 将clone方法声明为public
  • 如果有必要重写clone方法,则需要调用super.clone()
几个要点
  • Objectclone方法只通过JNI实现对象浅拷贝。
    • x.clone() != x
      返回的拷贝对象是开辟新的内存。
    • x.clone().getClass() == x.getClass()
    • x.clone().equals(x)
      “值相等”只是基本数据类型的值相等,而引用类型的引用相等。如果该类的成员对象只是基本数据类型以及不可变对象的引用类型,就无须重写clone方法,只需要把修饰符改成public。但是所以如果要实现深拷贝,则需要重写clone方法。而引用类型的深拷贝的实现同样按照以上的要求——实现Cloneable接口。
  • 如果没有实现Cloneable接口,而去调用clone方法的话则会抛出CloneNotSupportedException
  • 数组默认实现Cloneable接口,实现浅拷贝。
Object的clone方法
public class Object {
/**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. The general
     * intent is that, for any object {@code x}, the expression:
     * <blockquote>
     * <pre>
     * x.clone() != x</pre></blockquote>
     * will be true, and that the expression:
     * <blockquote>
     * <pre>
     * x.clone().getClass() == x.getClass()</pre></blockquote>
     * will be {@code true}, but these are not absolute requirements.
     * While it is typically the case that:
     * <blockquote>
     * <pre>
     * x.clone().equals(x)</pre></blockquote>
     * will be {@code true}, this is not an absolute requirement.
     * <p>
     * By convention, the returned object should be obtained by calling
     * {@code super.clone}.  If a class and all of its superclasses (except
     * {@code Object}) obey this convention, it will be the case that
     * {@code x.clone().getClass() == x.getClass()}.
     * <p>
     * By convention, the object returned by this method should be independent
     * of this object (which is being cloned).  To achieve this independence,
     * it may be necessary to modify one or more fields of the object returned
     * by {@code super.clone} before returning it.  Typically, this means
     * copying any mutable objects that comprise the internal "deep structure"
     * of the object being cloned and replacing the references to these
     * objects with references to the copies.  If a class contains only
     * primitive fields or references to immutable objects, then it is usually
     * the case that no fields in the object returned by {@code super.clone}
     * need to be modified.
     * <p>
     * The method {@code clone} for class {@code Object} performs a
     * specific cloning operation. First, if the class of this object does
     * not implement the interface {@code Cloneable}, then a
     * {@code CloneNotSupportedException} is thrown. Note that all arrays
     * are considered to implement the interface {@code Cloneable} and that
     * the return type of the {@code clone} method of an array type {@code T[]}
     * is {@code T[]} where T is any reference or primitive type.
     * Otherwise, this method creates a new instance of the class of this
     * object and initializes all its fields with exactly the contents of
     * the corresponding fields of this object, as if by assignment; the
     * contents of the fields are not themselves cloned. Thus, this method
     * performs a "shallow copy" of this object, not a "deep copy" operation.
     * <p>
     * The class {@code Object} does not itself implement the interface
     * {@code Cloneable}, so calling the {@code clone} method on an object
     * whose class is {@code Object} will result in throwing an
     * exception at run time.
     *
     * @return     a clone of this instance.
     * @throws  CloneNotSupportedException  if the object's class does not
     *               support the {@code Cloneable} interface. Subclasses
     *               that override the {@code clone} method can also
     *               throw this exception to indicate that an instance cannot
     *               be cloned.
     * @see java.lang.Cloneable
     */
    protected native Object clone() throws CloneNotSupportedException;
}
接口Cloneable
/**
 * A class implements the <code>Cloneable</code> interface to
 * indicate to the {@link java.lang.Object#clone()} method that it
 * is legal for that method to make a
 * field-for-field copy of instances of that class.
 * <p>
 * Invoking Object's clone method on an instance that does not implement the
 * <code>Cloneable</code> interface results in the exception
 * <code>CloneNotSupportedException</code> being thrown.
 * <p>
 * By convention, classes that implement this interface should override
 * <tt>Object.clone</tt> (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * <p>
 * Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
 * Therefore, it is not possible to clone an object merely by virtue of the
 * fact that it implements this interface.  Even if the clone method is invoked
 * reflectively, there is no guarantee that it will succeed.
 *
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */
public interface Cloneable {
}

利用串行化来实现深层复制

在Java语言里深层复制一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝)写到一个流中,再从流中读出来,便可以重建对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用以下几种方式进行对象拷贝: 1. 浅拷贝(Shallow Copy):使用`clone()`方法实现浅拷贝。浅拷贝只是复制了对象的引用,而不是创建一个新的对象。修改原对象拷贝对象的属性会相互影响。 ```java class MyClass implements Cloneable { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // 使用浅拷贝 MyClass obj1 = new MyClass(); obj1.setValue(10); MyClass obj2 = (MyClass) obj1.clone(); System.out.println(obj2.getValue()); // 输出 10 obj2.setValue(20); System.out.println(obj1.getValue()); // 输出 20,原对象也被修改了 ``` 2. 深拷贝(Deep Copy):通过序列化和反序列化实现深拷贝。深拷贝会创建一个新的对象,并复制对象的所有属性。修改原对象拷贝对象的属性不会相互影响。 ```java import java.io.*; class MyClass implements Serializable { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } public MyClass deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); MyClass copy = (MyClass) ois.readObject(); ois.close(); return copy; } } // 使用深拷贝 MyClass obj1 = new MyClass(); obj1.setValue(10); MyClass obj2 = obj1.deepCopy(); System.out.println(obj2.getValue()); // 输出 10 obj2.setValue(20); System.out.println(obj1.getValue()); // 输出 10,原对象不受影响 ``` 除了上述方法,还可以使用第三方库如Apache Commons的`SerializationUtils`类、Gson库等来实现对象的深拷贝

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值