将类枚举传递给克隆是否安全?
我有一个简单的类,它为更大、更笨重的类提供了骨架。所有这些骨架都是一个字符串 ID、一个类型枚举和一些选项标志。
我希望能够克隆这个骨架,但我不知道枚举是否是克隆安全的(按值传递)。我认为它们不是,因为它们被视为类(通过引用传递)。将枚举传递到克隆中是否安全?
为了清楚起见,示例:
class A {
String id;
Enum state;
int flags;
A clone() {
A ret = new A();
ret.id = id;
ret.state = state; // Am I safe here?
ret.flags = flags;
return ret;
}
}
I have a simple class that holds skeleton for a much larger, bulkier class. All this skeleton is is a string id, a type enumeration and some flags for options.
I would like to be able to clone this skeleton, but I don't know if the enumeration is clone safe (pass by value). I think that they are not since they are treated like classes (pass by reference). Is it safe to just pass the enumeration into the clone?
Example for clarity:
class A {
String id;
Enum state;
int flags;
A clone() {
A ret = new A();
ret.id = id;
ret.state = state; // Am I safe here?
ret.flags = flags;
return ret;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据定义,枚举实例是单例。根据设计,每个枚举实例只有一个实例。显然,您唯一能做的就是复制其引用。
An enum instance, by definition, is a singleton. There is only one instance of each enum instance, by design. So obviously, the only thing you can do is copy its reference.
JB Nizet的答案是正确的。而且,以防万一您试图覆盖
Object.clone()
,请注意 Java 中克隆对象的官方方法是这样的:请注意,您必须调用
(A) super.clone()
而不是new A()
,并且您的类必须实现Cloneable
接口。JB Nizet's answer is right. But also, just in case you were trying to override
Object.clone()
, be aware the official way of cloning objects in Java is something like this:Note that you must call
(A) super.clone()
instead ofnew A()
, and that your class must implement theCloneable
interface.