一个类要拷贝,首先要继承接口Cloneable
package com.mao.hah;
public class AnotherClass implements Cloneable{
private int x;
public AnotherClass()
{
x=12;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public Object clone() {
AnotherClass o = null;
try {
o = (AnotherClass) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
测试代码:
package com.mao.hah;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TestClass {
public static void main(String args[]) throws ParseException
{
AnotherClass a=new AnotherClass();
System.out.println("原始值是:"+a.getX());
TestClass t=new TestClass();
t.ChangeX((AnotherClass)a.clone());
System.out.println("传参改变还是原来的值:"+a.getX());
}
public void ChangeX(AnotherClass a)
{
a.setX(14);
}
}