gpt4 book ai didi

Java:防止在方法外部使用对象引用

转载 作者:搜寻专家 更新时间:2023-11-01 02:51:51 25 4
gpt4 key购买 nike

我定义了一个接口(interface)RecordVisitor,声明如下:

public interface RecordVisitor<K, V, Result> {
public Result visit(Record<K, V> rec);
}

想法是 visit 的实现将使用 Record 对象调用,执行它们的逻辑并返回结果。我想防止实现隐藏 rec 值并在 visit 调用之外使用它。

我想做到这一点的唯一方法是将状态添加到 Record,如果在 record 对象上调用任何方法而它没有调用则抛出 IllegalStateException “积极的”。然后我会在 javadoc 中写入可怕的警告,并希望实现者阅读它。

是否有更可靠的方法来防止在 visit 方法之外使用 Record 对象?如果可能的话,我想构建一个接口(interface),如果违反约定,该接口(interface)会导致编译时错误。

最佳答案

没有办法阻止实现者将对对象的引用存储为他们实现visit的一部分。

然而,这里还有一个更大的哲学问题。如果您不信任实现 RecordVisitor 接口(interface)的代码,那么您为什么要使用该代码?如果这样做,那么如果该代码保留对对象的引用,为什么会出现问题?

The only way I've thought to do this is by adding state to Record, and throwing IllegalStateException if any method is called on the record object while it is not "active".

如果您不信任正在实现您的 RecordVisitor 接口(interface)的程序员,这仍然不够。没有什么可以阻止实现者创建新方法

public void foo() {
this.rec.activate();
// Do something, and there is no IllegalStateException
this.rec.deactivate();
}

Record 将显示为来自 visit 内部的调用,但实际上不会来自 visit 内部。

关于Java:防止在方法外部使用对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com