Good morning dear board
There is a way in Java to make instances of anonymous classes:
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod ("method name", parameterTypes)
method.invoke (objectToInvokeOn, params)
If I wished making new Instances of JavaFX Controllers I would just do this:
FXMLLoader loader = new FXMLLoader(getClass().getResource(
"MyClass.fxml"));
MyClassCtrl ctrl = loader.getController();
Parent root = (Parent) loader.load();
ctrl.methodNameOfMyClassCtrl();
But now I have an example where I need to do instances of Controllers and use their methods, which aren't known while coding. They get known by runtime, depends on which Button was clicked by the user.
So what I need is a combination of the both techniques descriped above. Now I made following, but it won't work.
String methodName = "myMethod";
String className = "MyController";
FXMLLoader loader = new FXMLLoader(getClass().getResource( className + ".fxml" ));
Class c = Class.forName(className);
loader.setController(c);
Parent root = (Parent) loader.load();
Method m = c.getDeclaredMethod(methodName, null);
m.invoke(null, null);
I doubt, I'm the first trying something like this - so you guys are my last chance.
Thanks and best regards Enis
If you really want to mix reflection API with your controllers, see this
String methodName = "myMethod";
String className = "MyController";
FXMLLoader loader = new FXMLLoader(getClass().getResource( className + ".fxml" ));
Class c = Class.forName("mypackage." + className);
Object obj = c.newInstance();
loader.setController(obj);
Parent root = (Parent) loader.load();
Method m = c.getDeclaredMethod(methodName);
m.invoke(obj);
However bear in mind that reflection maybe slow down your app speed and refactoring maybe hard to do. If you explain your use case there can be other approach using OOP like inheritance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.