我查看了 Property API,发现 ReadOnly 属性实际上是 Properties 的子类。我一开始认为这很好,因为一旦一个对象是 ReadOnlyProperty
它无法重新获得 Property
内部的方法。然而事实并非如此,您可以轻松地进行类型转换以完全绕过只读部分。
public static void change(ReadOnlyIntegerProperty y)
{
if (y instanceof IntegerProperty)
{
IntegerProperty z = (IntegerProperty)y;
z.set(10);
}
}
这是有意设计的吗?我知道 ReadOnlyProperties 对于程序员来说更像是一个指南。但这实际上是否意味着在JavaFX api中,某些属性以只读方式提供,然后可以更改?例如:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html
public final ReadOnlyObjectProperty<Scene> sceneProperty
我可以简单地将其转换为 ObjectProperty<Scene>
现在我可能会导致库中出现未定义的行为。
我正在尝试实现Property
使用另一种不支持它们的语言。有什么好方法可以防止这种情况发生?
最佳答案
您应该使用一个ReadOnlyIntegerWrapper
,它有一个可写部分和一个只读部分。可写部分是您可以在内部使用的部分,就好像它是普通属性一样,只读部分是您返回给调用者的部分:
public class Test {
private final ReadOnlyIntegerWrapper foo = new ReadOnlyIntegerWrapper();
public Test() {
foo.set(42);
}
public final javafx.beans.property.ReadOnlyIntegerProperty fooProperty() {
return this.foo.getReadOnlyProperty();
}
public final int getFoo() {
return this.fooProperty().get();
}
}
关于JavaFX - ReadOnlyProperty 不是只读的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305297/