从你的问题我猜你需要深拷贝的对象。如果是这种情况,请不要使用clone
方法,因为它已经在oracle docs
中指定它提供浅拷贝的关联对象。我对BeanUtils.copyProperties
API没有足够的了解。
以下是deep copy
的简短演示。在这里我深刻地复制了primitive array
。您可以使用任何类型的对象来尝试此代码。
import java.io.*;
class ArrayDeepCopy
{
ByteArrayOutputStream baos;
ByteArrayInputStream bins;
public void saveState(Object obj)throws Exception //saving the stream of bytes of object to `ObjectOutputStream`.
{
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
}
public int[][] readState()throws Exception //reading the state back to object using `ObjectInputStream`
{
bins = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream oins = new ObjectInputStream(bins);
Object obj = oins.readObject();
oins.close();
return (int[][])obj;
}
public static void main(String[] args) throws Exception
{
int arr[][]= {
{1,2,3},
{4,5,7}
};
ArrayDeepCopy ars = new ArrayDeepCopy();
System.out.println("Saving state...");
ars.saveState(arr);
System.out.println("State saved..");
System.out.println("Retrieving state..");
int j[][] = ars.readState();
System.out.println("State retrieved..And the retrieved array is:");
for (int i =0 ; i < j.length ; i++)
{
for (int k = 0 ; k < j[i].length ; k++)
{
System.out.print(j[i][k]+"\t");
}
System.out.print("\n");
}
}
}
那你到底在问什么? – 2013-03-21 08:29:16
我们应该使用clone还是BeanUtils.copyProperties,为什么 – Biscuit128 2013-03-21 08:32:09