Java 克隆内部类的对象
我已经写了一篇a类文章,如下所示Java 克隆内部类的对象,java,Java,我已经写了一篇a类文章,如下所示 class A <E> { // class A has objects of E int x; private B<T> next // a object of inner class class B<T> { // an inner class having objects of type T T[] elements = (T[]) Object[x];
class A <E> { // class A has objects of E
int x;
private B<T> next // a object of inner class
class B<T> {
// an inner class having objects of type T
T[] elements = (T[]) Object[x];
// has other stuff including many objects
}
public A<E> func ( B<E> val ){
Here I want to clone the value of val so that I can do different operations on other
}
class A{//class A的对象是E
int x;
private B next//内部类的对象
B类{
//具有T类型对象的内部类
T[]元素=(T[])对象[x];
//还有其他的东西,包括很多东西
}
公共A功能(B val){
在这里,我想克隆val的值,以便我可以在其他服务器上执行不同的操作
}
问题是,我希望编写B Temp=BValue.clone()
,其中值在代码中定义
但它说克隆是不可见的
我该怎么做才能做到这一点
非常感谢…克隆()受到保护,因此您只需在B中重新定义即可执行所需操作。最好不要使用
clone()
,而是在B
上实现复制构造函数:
class B extends A {
// an inner class having objects of type
List<String> strings = ArrayList<String>();
public B(B that) {
super(that); // call the superclass's copy constructor
this.strings = new ArrayList<String>();
this.strings.add(that.strings);
}
// ...
}
(删除泛型内容以限制复制构造函数本身的演示)这里是Peter答案的示例(未测试,可能需要一些语法检查):
class A{//class A的对象是E
int x;
private B next//内部类的对象
类实现了可克隆性{
公共B克隆(){
试一试{
B klon=(B)super.clone();
//TODO:也许还可以克隆阵列?
返回克伦;
}
捕获(CloneNotSupportedException){
//不应该发生
抛出新错误(“程序员很愚蠢”);
}
}
//具有T类型对象的内部类
T[]元素=(T[])对象[x];
//还有其他的东西,包括很多东西
}
公共A功能(B val){
B clone=val.clone();
//更多代码
}
您能否提供包含您的克隆()的代码示例
routine?您可能还想实现Cloneable
接口。重定义是什么意思?您能举个例子吗?比如我需要在嵌套类中实现Cloneable,或者什么?只需覆盖它并增加它的可见性:将其公开。在内部,您将调用super.clone()然后——如果需要的话——你将制作一个深度副本。你能再举一个例子吗……我在内部类中编写了super.clone(),eclipse不允许我运行它。非常感谢……克隆被破坏了,关于“最好不要使用克隆()”这个主题(示例:)有很多问题和答案,如果您正在克隆B
类型,但不确定其运行时类型(因为它可能是B
的子类),该怎么办?@Steve Kuo-我不理解这个评论。AB
在运行时是AB
,B的子类不是AB
。子类化不是问题的一部分,但无论如何,我编辑了这个问题。复制构造函数与继承是兼容的。(而且clone
仍然是坏的,我们应该简单地避免它).BB
的子类如何不是aB
(它将传递instanceof)?你是说LinkedHashMap
不是HashMap
?@Steve-aLinkedHashMap
是LinkedHashMap
的一个扩展HashMap
。你可以通过调用LinkedHashMap
构造函数来创建它。在LinkedHashMap
的实例上调用getClass()
返回“java.util.LinkedHashMap”
.is-a在本例中是含糊不清的,我不是在谈论继承,而是在谈论实例的类型。
public C func ( B val ){
B clone = new B(val);
}
class A <E> { // class A has objects of E
int x;
private B<T> next // a object of inner class
class B<T> implements Cloneable {
public B<T> clone() {
try {
B<T> klon = (B<T>) super.clone();
// TODO: maybe clone the array too?
return klon;
}
catch(CloneNotSupportedException) {
// should not occur
throw new Error("programmer is stupid");
}
}
// an inner class having objects of type T
T[] elements = (T[]) Object[x];
// has other stuff including many objects
}
public A<E> func ( B<E> val ){
B<E> clone = val.clone();
// more code
}