gpt4 book ai didi

java - CloneNotSupportedException 即使在实现 Cloneable 时也是如此

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:14 25 4
gpt4 key购买 nike

为什么以下代码在 JDK7 中抛出 CloneNotSupportedException 而在 JDK6 中不抛出

public class DemoThread extends Thread implements Cloneable {

/**
* @param args
*/
public static void main(String[] args) {
DemoThread t = new DemoThread();
t.cloned();
}

public DemoThread cloned()
{
try {
return (DemoThread) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}

}

最佳答案

这是 Thread 在 SE 7 中对 clone() 的实现

/**
* Throws CloneNotSupportedException as a Thread can not be meaningfully
* cloned. Construct a new Thread instead.
*
* @throws CloneNotSupportedException
* always
*/
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

线程从未被设计为被克隆。做一些阅读引发了其中一条评论,我发现这总结得很好:"But we either have to disallow cloning or give it meaningful semantics - and the latter isn't going to happen." -- 大卫·霍姆斯

关于java - CloneNotSupportedException 即使在实现 Cloneable 时也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14052219/

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