JavaFX-ReadOnlyProperty不是只读的
我浏览了属性API,发现只读属性实际上是属性的一个子类。起初我认为这很好,因为一旦对象成为JavaFX-ReadOnlyProperty不是只读的,java,javafx,properties,Java,Javafx,Properties,我浏览了属性API,发现只读属性实际上是属性的一个子类。起初我认为这很好,因为一旦对象成为只读属性,它就无法恢复属性中的方法。然而,事实并非如此,您可以轻松地进行类型转换以完全绕过只读部分 public static void change(ReadOnlyIntegerProperty y) { if (y instanceof IntegerProperty) { IntegerProperty z = (IntegerProperty)y;
只读属性
,它就无法恢复属性
中的方法。然而,事实并非如此,您可以轻松地进行类型转换以完全绕过只读部分
public static void change(ReadOnlyIntegerProperty y)
{
if (y instanceof IntegerProperty)
{
IntegerProperty z = (IntegerProperty)y;
z.set(10);
}
}
这是故意的吗?我知道ReadOnlyProperty更像是程序员的指南。但实际上这不意味着在JavaFXAPI中,某些属性是只读的,然后可以更改吗?例如:
public final ReadOnlyObjectProperty sceneProperty
我可以简单地将其转换为
ObjectProperty
,现在可能会导致库中出现未定义的行为
我试图用另一种不支持它们的语言实现
属性。防止这种情况发生的好方法是什么?您应该使用一个具有可写和只读部分的ReadOnlyIntegraterRapper
。可写部分是您可以在内部使用的,就像它是普通属性一样,只读部分是您返回给调用方的部分:
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();
}
}
您应该使用一个具有可写和只读部分的readonlyintegerrapper
。可写部分是您可以在内部使用的,就像它是普通属性一样,只读部分是您返回给调用方的部分:
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();
}
}
“只读属性实际上是属性的一个子类”。这不是真的;反过来说。是只读属性
的子接口。API可以从具有返回类型ReadOnlyProperty
的方法返回(完全可写的)属性的实例,但正如其他注释和回答中指出的那样,您不应该这样做-而是使用ReadOnlyWrapper
,或者返回一个未实现writeablevalue
的ReadOnlyProperty
实现“我可以简单地将其转换为ObjectProperty
”。你试过这个吗?至少在Java9.0.4和更高版本中,我得到了“Java.lang.ClassCastException:javafx”。base@9.0.4/javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl不能强制转换为javafx。base@9.0.4/“只读属性实际上是属性的一个子类”。这不是真的;反过来说。是只读属性
的子接口。API可以从具有返回类型ReadOnlyProperty
的方法返回(完全可写的)属性的实例,但正如其他注释和回答中指出的那样,您不应该这样做-而是使用ReadOnlyWrapper
,或者返回一个未实现writeablevalue
的ReadOnlyProperty
实现“我可以简单地将其转换为ObjectProperty
”。你试过这个吗?至少在Java9.0.4和更高版本中,我得到了“Java.lang.ClassCastException:javafx”。base@9.0.4/javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl不能强制转换为javafx。base@9.0.4/javafx.beans.property.ObjectProperty“。由getReadOnlyProperty
返回的ReadOnlyIntegerProperty
实际上不是IntegerProperty
(或WritableValue
)的实例,因此尝试执行OP描述的操作(“调用者仍可以按照您的建议使用内省”)只会导致类强制转换异常。@James\D我明白了。很高兴知道。谢谢!明白了。我想一定有这样的把戏。不幸的是,只读属性和可写属性不能同时指向同一个对象,但这会使它受到我上面描述的攻击。无论如何,谢谢!由getReadOnlyProperty
返回的ReadOnlyIntegerProperty
实际上不是IntegerProperty
(或writeablevalue
)的实例,因此尝试执行OP描述的操作(“调用方仍可以按照您的建议使用内省”)只会导致类强制转换异常。@James\D我明白了。很高兴知道。谢谢!明白了。我想一定有这样的把戏。不幸的是,只读属性和可写属性不能同时指向同一个对象,但这会使它受到我上面描述的攻击。无论如何,谢谢!