为什么无法克隆 java.lang.Object?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11344814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why java.lang.Object can not be cloned?
提问by amicngh
When i try to clone a generic Objecti get compile time error . why?
当我尝试克隆通用对象时,出现编译时错误。为什么?
Object obj=new Object();
obj.clone(); // Here compile time error "The method clone() from the type Object is not visible"
Every class extends Objectclass and clone method is protected in Objectclass.
每个类都扩展了Object类,并且克隆方法在Object类中受到保护。
protected
methods can be accessed in same package as well as by subclasses
and all classes are child of java.lang.Object
.
protected
方法可以在同一个包中访问,subclasses
并且所有类都是java.lang.Object
.
回答by Louis Wasserman
Because clone
is protectedin the Object
class. It's not public
.
因为clone
被保护的Object
类。不是public
。
The only way to get access to an object's clone()
method is to know it has a compile-time type that has a public clone()
method.
访问对象clone()
方法的唯一方法是知道它有一个具有公共clone()
方法的编译时类型。
回答by Steve Townsend
Per the Java SE docs:
根据Java SE 文档:
The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.
类 Object 本身并不实现接口 Cloneable,因此在类为 Object 的对象上调用 clone 方法将导致在运行时抛出异常。
回答by Marko Topolnik
This will be the minimum to get clone working:
这将是让克隆工作的最低要求:
public class SubObj implements Cloneable {
public Object clone() { return super.clone(); }
}
回答by Eng.Fouad
protected
fields can be accessed only from inside the same package, thus clone()
method of Object
class can be accessed only from any class that is located in java.lang
package.
protected
字段只能从同一个包内部访问,因此类的clone()
方法Object
只能从位于java.lang
包中的任何类访问。
回答by avgvstvs
If you use Groovy so that you can bypass the java compilation error, you get this:
如果您使用 Groovy 来绕过 java 编译错误,则会得到以下信息:
Exception in thread "main" java.lang.CloneNotSupportedException: java.lang.Object
at java.lang.Object.clone(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:86)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:230)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:912)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:756)
at org.codehaus.groovy.runtime.InvokerHelper.invokePojoMethod(InvokerHelper.java:766)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:754)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:170)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethod0(ScriptBytecodeAdapter.java:198)
at regexTests.main(regexTests.groovy:19)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]
If you read the clone API (I will link it) it says that if the Interface isn't implemented, then calling *.clone() will throw a CloneNotSupportedException
.
如果您阅读了克隆 API(我将链接它),它会说如果未实现接口,则调用 *.clone() 将抛出一个CloneNotSupportedException
.
Link to the clone API for java.lang.Object
http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29
链接到http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29的克隆 APIjava.lang.Object
[EDIT]
The Original Question? asked for why this method is visible in the way it is. This is because it only accessible to methods within the java.lang package. It isn't intended for a programmer to be able to clone an Object
. Throwing a CloneNotSupportedException
is exactly what you want to do if you don't want your OWN object cloned.
[编辑] 最初的问题?询问为什么这种方法以这种方式可见。这是因为它只能被 java.lang 包中的方法访问。程序员不应该能够克隆Object
. CloneNotSupportedException
如果您不想克隆自己的对象,那么抛出 a正是您想要做的。
回答by Ratheesh
void method() {
Object obj=new Object(); //Object is a parent class, it's not inherit from any other class...
obj.clone(); // compile time error
}
We can't access the protected method of "Has A" relationship from different package, because your Class package is (com.xxx.yyy) and an Object class package is (java.lang) both the classes are in different package.
我们无法从不同的包中访问“Has A”关系的protected 方法,因为你的Class 包是(com.xxx.yyy) 而一个Object 类包是(java.lang) 两个类都在不同的包中。
protected methods can be accessed in same package as well as by subclasses(IS A relationship)
受保护的方法可以在同一个包中以及子类中访问(IS 关系)
回答by Adelin
I tried this code :
我试过这个代码:
public final class User {
private String name;
private boolean isActive;
private String userId;
private Address address;
// can be constructed using this constructor ONLY !
public User(String name, boolean isActive, String userId, Address address) {
this.name = name;
this.isActive = isActive;
this.userId = userId;
this.address = address;
}
public String getName() {
return name;
}
public boolean isActive() {
return isActive;
}
public String getUserId() {
return userId;
}
public Address getAddress() {
return address;
}
protected Object cloneMe() throws CloneNotSupportedException {
return super.clone(); // throws CloneNotSupportedException
}
}
public class CloneNotSupportedException extends Exception
公共类 CloneNotSupportedException 扩展异常
Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface. Applications that override the clone method can also throw this exception to indicate that an object could not or should not be cloned.
抛出表示已调用类 Object 中的 clone 方法来克隆对象,但该对象的类未实现 Cloneable 接口。覆盖 clone 方法的应用程序也可以抛出此异常以指示不能或不应克隆对象。
Object doesn't implement any interface and to make my User class work it must implement Cloneable
对象不实现任何接口,为了使我的用户类工作它必须实现 Cloneable
回答by Manoj Ekanayaka
Object class clone() method has modified by protected access modifier in the API level. So we can't access it anywhere without inheritance. So before we invoke object class clone() method you need to implements Cloneable interface. Then Code will run at runtime properly. Otherwise it will generate CloneNotSupportedException at runtime.
对象类 clone() 方法已被 API 级别的 protected 访问修饰符修改。所以我们不能在没有继承的情况下在任何地方访问它。因此,在我们调用对象类 clone() 方法之前,您需要实现 Cloneable 接口。然后代码将在运行时正常运行。否则它会在运行时生成 CloneNotSupportedException。
/*Subclass is my implementing class */
public class SubClass implements Cloneable {
@Override
public SubClass clone() throws CloneNotSupportedException {
return (SubClass) super.clone();
}
}
回答by Arcadien
You must explicitely implements Cloneable interface. see this threadwhich give explanations.
您必须明确实现 Cloneable 接口。请参阅此线程,其中给出了解释。