Java中如何克隆一个对象?
    		       		warning:
    		            这篇文章距离上次修改已过430天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中,克隆一个对象通常涉及实现Cloneable接口并重写clone()方法。以下是一个简单的例子:
public class MyClass implements Cloneable {
    private int value;
 
    public MyClass(int value) {
        this.value = value;
    }
 
    // Getter and Setter
    public int getValue() {
        return value;
    }
 
    public void setValue(int value) {
        this.value = value;
    }
 
    // Clone method
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
 
    // Main method for demonstration
    public static void main(String[] args) {
        try {
            MyClass original = new MyClass(10);
            MyClass clone = (MyClass) original.clone();
 
            // Check that the clone is independent of the original
            System.out.println(original.getValue()); // Output: 10
            System.out.println(clone.getValue());     // Output: 10
 
            // Modify the value of the clone
            clone.setValue(20);
 
            // Check that the original object is not affected
            System.out.println(original.getValue()); // Output: 10
            System.out.println(clone.getValue());     // Output: 20
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}在这个例子中,MyClass实现了Cloneable接口,并重写了clone()方法。在main方法中,我们创建了一个MyClass对象的克隆,并修改了克隆的value属性,以展示克隆对象是独立于原对象的。
评论已关闭