java如何使字段不可复制

Sun*_*day 3 java cloneable

对于序列化,将排除瞬态字段.克隆有没有类似的关键词?如何从克隆中排除字段?

public class Foo implements Cloneable {
    private Integer notInClone;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

如果您希望它是公共的(它不是接口的一部分,并且在其中),您必须实现,您将有机会清除代码中不需要的字段:clone()CloneableprotectedObject

public Object clone() throws CloneNotSupportedException {
    Foo res = (Foo)super.clone();
    res.notInClone = null;        // Do the cleanup for fields that you wish to exclude
    return res;
}
Run Code Online (Sandbox Code Playgroud)

演示.