为什么这段代码会抛出CloneNotSupportedException?
public class Car {
private static Car car = null;
private void car() {
}
public static Car GetInstance() {
if (car == null) {
car = new Car();
}
return car;
}
public static void main(String arg[]) throws CloneNotSupportedException {
car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());// getting the hash code
System.out.println(car1.hashCode());
}
}
答案 0 :(得分:2)
如果您正在克隆单例对象,那么您违反了Singleton的设计原则。
默认情况下,clone
方法受到保护:protected native Object clone() throws CloneNotSupportedException
;
如果您的Car
扩展了另一个支持克隆的类,则可能会违反单例的设计原则。因此,绝对肯定100%确定单身实际上是单身,我们必须添加我们自己的clone()
方法,如果有人试图创建,则抛出CloneNotSupportedException
。下面是我们的覆盖克隆方法。
@Override
protected Object clone() throws CloneNotSupportedException {
/*
* Here forcibly throws the exception for preventing to be cloned
*/
throw new CloneNotSupportedException();
// return super.clone();
}
请找到以下代码块来处理Clone for Singleton类或通过取消注释代码来避免克隆。
public class Car implements Cloneable {
private static Car car = null;
private void Car() {
}
public static Car GetInstance() {
if (car == null) {
synchronized (Car.class) {
if (car == null) {
car = new Car();
}
}
}
return car;
}
@Override
protected Object clone() throws CloneNotSupportedException {
/*
* Here forcibly throws the exception for preventing to be cloned
*/
// throw new CloneNotSupportedException();
return super.clone();
}
public static void main(String arg[]) throws CloneNotSupportedException {
car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());// getting the hash code
System.out.println(car1.hashCode());
}
}
答案 1 :(得分:0)
public class Car implements Cloneable {
private static Car car = null;
public static Car GetInstance() {
if (car == null) {
car = new Car();
}
return car;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Car car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());
System.out.println(car1.hashCode());
<强>输出:强>
1481395006
2027946171