-1

为什么这段代码会抛出 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());
    }
}
4

2 回答 2

2

如果您正在克隆单例对象,那么您就违反了单例的设计原则。

默认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();
    }

请找到下面的代码块来为 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());
    }
}    
于 2016-06-22T08:01:03.510 回答
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
于 2013-10-10T09:35:54.077 回答