将类枚举传递给克隆是否安全?

发布于 2024-12-27 11:49:30 字数 410 浏览 2 评论 0原文

我有一个简单的类,它为更大、更笨重的类提供了骨架。所有这些骨架都是一个字符串 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赴月观长安 2025-01-03 11:49:30

根据定义,枚举实例是单例。根据设计,每个枚举实例只有一个实例。显然,您唯一能做的就是复制其引用。

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.

无声无音无过去 2025-01-03 11:49:30

JB Nizet的答案是正确的。而且,以防万一您试图覆盖 Object.clone(),请注意 Java 中克隆对象的官方方法是这样的:

class A implements Cloneable {
    String id;
    Enum state;
    int flags;

    public A clone() {
        A ret = (A) super.clone();
        ret.id = id;
        ret.state = state;  // Enum is a singleton, so this is ok
        ret.flags = flags;
        return ret;
    }
}

请注意,您必须调用 (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:

class A implements Cloneable {
    String id;
    Enum state;
    int flags;

    public A clone() {
        A ret = (A) super.clone();
        ret.id = id;
        ret.state = state;  // Enum is a singleton, so this is ok
        ret.flags = flags;
        return ret;
    }
}

Note that you must call (A) super.clone() instead of new A(), and that your class must implement the Cloneable interface.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文