java - 为什么在java中克隆对象时出现运行时异常
问题描述
我正在尝试执行对象的浅克隆我的狗类有一个原始变量 i=10,还有一个指向对象 j=20 的引用变量,而且我将克隆方法定义为公共但是我得到了运行时错误在线程“主”java.lang.CloneNotSupportedException 中说异常
package com.objectclasscoding.practice;
import com.objectclasscoding.practice.Cat.Dog;
class Cat {
int j;
public Cat(int j) {
this.j = j;
}
class Dog implements Cloneable {
Cat c;
int i;
public Dog(Cat c, int i) {
this.c = c;
this.i = i;
}
}
public Object clone() throws CloneNotSupportedException {
return (Dog) super.clone();
}
}
public class ShallowCloningDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c = new Cat(20);
Dog d1 = c.new Dog(c, 10);
System.out.println(d1.i + ".." + c.j);
Dog d2 = (Dog) d1.c.clone();
d1.i = 888;
d1.c.j = 999;
System.out.println(d2.i + ".." + d2.c.j);
}
}
运行此代码后,我收到运行时错误消息Exception in thread "main" java.lang.CloneNotSupportedException
解决方案
您似乎正在调用 clone ond1.c
的一个实例Cat
,它没有实现Cloneable
。
For some reason you've added a clone()
method to Cat
rather than Dog
. Inside that method, you tried to cast the result to Dog
, as if a cloned Cat
would be an instance of Dog
. That does not make sense. Cats are notoriously not the same as dogs.
推荐阅读
- c# - swagger-ui 中默认的 api 版本值
- html - 如何更改现有的 Atom.io Snippets
- javascript - 无法获取 Packery 项目布局顺序
- mongodb - 如何计算所有手机号码在mongo查询中的收费次数
- c# - 使用 SqlCommand 执行时可能导致链接服务器查询失败的原因是什么?
- php - 我有一个视图无法通过我的控制器连接到我的登录模型
- json - 请求正文验证
- python-3.x - 协助添加多个骰子
- sql - 在oracle sql中将4229,4转换为4229.4000000
- kubernetes - 简化 Kubernetes RBAC 定义的创建