JavaFx:fxmlLoader.loadreturnsParent?
JavaFx: fxmlLoader.load returns Parent?
我在 fxml 文件的根级别有 ScrollPane,我有以下代码:
import javafx.scene.Parent;
...
parent = (Parent)fxmlLoader.load(getFxmlStream("my.fxml"));
if (parent.getClass().isAssignableFrom(Parent.class)){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
为什么无法从 Parent class 分配什么加载函数 returns?
来自Javadocs for isAssignableFrom
:
Determines if the class or interface represented by this Class object
is either the same as, or is a superclass or superinterface of, the
class or interface represented by the specified Class parameter.
因此,您正在测试从 FXML 加载器获得的对象的运行时类型是否等于 超类 Parent
。如果它是 Parent
的严格子类(VBox
、BorderPane
等),那么它将是 false
.
如果您想测试您拥有的值是否是某种 Parent
,通常的方法是使用 instanceof
:
if (parent instanceof Parent)){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
如果你想使用 getClass()
和 isAssignableFrom()
,那么你的方法就错了:
if (Parent.class.isAssignableFrom(parent.getClass())){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
虽然我还是推荐标准 instanceof
方法。
另请注意,您几乎可以使用 FXML 加载任何对象,因此当然不能保证您得到的是 Parent
.
的子类
我在 fxml 文件的根级别有 ScrollPane,我有以下代码:
import javafx.scene.Parent;
...
parent = (Parent)fxmlLoader.load(getFxmlStream("my.fxml"));
if (parent.getClass().isAssignableFrom(Parent.class)){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
为什么无法从 Parent class 分配什么加载函数 returns?
来自Javadocs for isAssignableFrom
:
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
因此,您正在测试从 FXML 加载器获得的对象的运行时类型是否等于 超类 Parent
。如果它是 Parent
的严格子类(VBox
、BorderPane
等),那么它将是 false
.
如果您想测试您拥有的值是否是某种 Parent
,通常的方法是使用 instanceof
:
if (parent instanceof Parent)){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
如果你想使用 getClass()
和 isAssignableFrom()
,那么你的方法就错了:
if (Parent.class.isAssignableFrom(parent.getClass())){
System.out.println("THIS IS PARENT");
}else{
System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}
虽然我还是推荐标准 instanceof
方法。
另请注意,您几乎可以使用 FXML 加载任何对象,因此当然不能保证您得到的是 Parent
.