如何知道java中的对象是否支持克隆?或者它有副本 C'tor ?在运行时
请举个例子,谢谢
检查是否支持克隆检查
if(myObject instanceof Cloneable) {
}
以上将告诉您该对象是否实现了 Cloneable 并且是否支持默认克隆。
但是在某些情况下,类不支持克隆方法,但它们为您提供了一些 API,这些 API 将创建实例的副本,对于此类方法,您必须查看 API 文档或源代码。
更新:为什么 instanceof 检查不能保证成功克隆:
if(myObject instanceof Cloneable) {
Object obj = myObject.clone();
}
1->考虑下面的代码片段
public class IImplementCloneableButThrowException implements Cloneable{
//Javadoc has a separate section for Exception, implementation like
//this and should clearly specify the condition in which
//CloneNotSupportedException will be thrown.
public Object clone() throws CloneNotSupportedException {
//I implement but still wont clone, may be in future will allow myself to be cloned
throw new CloneNotSupportedException("Sorry I cannot be cloned!");
}
}
2-> 考虑下面的第二种情况
public class IImplementCloneableButCloneIsHidden implements Cloneable{
//Ouch either no clone method or one which is Object class but that
//has protected access modifier, which means I cannot call unless
//I extend it, too bad
}
因此,尽管instanceof
检查会正确通过,但要么clone
不能被调用,要么clone
会抛出异常。
所有支持的对象clone
都应该实现Cloneable
.