我正在使用Java 8桌面應用程序使用JavaFX 8。
我在MainApp類(擴展應用程序類的那個)中有此方法。如何編寫接受類類型作爲參數並使用它來投射某些對象的方法
public void showUserLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/userLayout.fxml"));
AnchorPane userPane = (AnchorPane) loader.load();
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add(userPane);
userLayoutController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}
我對每個我想要加載的佈局使用相同的代碼。
有什麼辦法來創建一個接受類類型作爲參數並做完全相同的工作,例如方法:
public void genericLayoutLoader(String fxmlFilename, Class rootFXMLElement, Class fxmlController) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource(fxmlFilename));
// Not sure for the Object below
Object chooseUserAndInterval = (rootFXMLElement) loader.load();
// rootAnchorPane is same for every layout
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add((rootFXMLElement) chooseUserAndInterval);
Object controller = (fxmlController) loader.getController();
((fxmlController)controller).setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}
我會用這樣的:
public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane, userLayoutController);
}
有什麼辦法可以實現這種行爲?
難道你不能通過讓所有人都實現一些通用接口來解決它嗎? – KDM
你的意思是類似[在這個答案](http://stackoverflow.com/questions/14524751/cast-object-to-generic-type-for-returning/14524815#14524815)? – SpaceTrucker
@KDM'showSomeLayout'方法全部在MainApp類中定義。所以,考慮到這一點,我認爲這不可行,對吧? – Chris