gpt4 book ai didi

java - 关于Cloneable接口(interface)和应该抛出的异常的问题

转载 作者:行者123 更新时间:2023-12-03 21:29:05 25 4
gpt4 key购买 nike

Java 文档说:

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

我有这个 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);
}
}

为了测试海豚,我在 main() 中这样做:

UserProfile up1 = new UserProfile("User", 123, "Street");
UserProfile up2 = up1.clone();

到目前为止,编译/运行没有问题。现在,根据我对文档的理解,从 UserProfile 类中删除 implements Cloneable 应该会在 up1.clone() 调用中引发异常,但是它没有。

我在这里读到 Cloneable 接口(interface)坏了,但我真的不知道那是什么意思。我错过了什么吗?

最佳答案

Now, per my understanding of the documentation, removing implements Cloneable from the UserProfile class should throw and exception in up1.clone() call, but it doesn't.

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

Object 中的 clone() 的实现是抛出异常的原因,但您已经覆盖了该方法。

关于java - 关于Cloneable接口(interface)和应该抛出的异常的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2888719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com