有关Cloneable接口和应抛出的异常的问题

Ric*_*ral 2 java clone interface exception cloneable

Java文档说:

类实现了Cloneable接口,以向Object.clone()方法指示该方法合法地为该类的实例制作字段的字段副本.

在未实现Cloneable接口的实例上调用Object的clone方法会导致抛出异常CloneNotSupportedException.

按照惯例,实现此接口的类应使用公共方法覆盖Object.clone(受保护).有关重写此方法的详细信息,请参阅Object.clone().

请注意,此接口不包含克隆方法.因此,仅仅通过实现该接口的事实来克隆对象是不可能的.即使反射调用clone方法,也无法保证它会成功.

我有这UserProfile堂课:

public class UserProfile implements Cloneable {
    private String name;
    private int ssn;
    private String address;

    public UserProfile(String name, int ssn, String address) {
        this.name = name;
        this.ssn = ssn;
        this.address = address;
    }

    public UserProfile(UserProfile user) {
        this.name = user.getName();
        this.ssn = user.getSSN();
        this.address = user.getAddress();
    }

    // get methods here...

    @Override
    public UserProfile clone() {
        return new UserProfile(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了测试porpuses,我这样做main():

UserProfile up1 = new UserProfile("User", 123, "Street");
UserProfile up2 = up1.clone();
Run Code Online (Sandbox Code Playgroud)

到目前为止,编译/运行没有问题.现在,根据我对文档的理解,implements CloneableUserProfile类中删除应该在up1.clone()调用中抛出异常,但事实并非如此.

我在这里读到Cloneable界面已经破解,但我真的不知道这意味着什么.我错过了什么吗?

Jes*_*per 5

现在,根据我对文档的理解,implements CloneableUserProfile类中删除应该在up1.clone()调用中抛出异常,但事实并非如此.

只要你的类仍然有一个clone()方法的实现,当你调用它时不会抛出异常 - 它就像任何其他方法一样工作,没有特殊的魔法.

的实现clone()Object就是抛出异常,但你重写该方法.