Do you know Java: Instance from static launcher
Instantiate the current class from its entry point by using static method. Interesting, isn’t it?
I came across with JavaFX recently, and I saw an example about how to use it. This made me think, and brought the following question in my mind. How can we make an instance of the class that is the starting point of our application and how can we call its instance methods.
Let us see the code that we have if we start building a javafx application.
class Hello extends Application {
@Override
public void start(Stage stage) {
}
public static void main(String[] args) {
launch(args);
}
}
As it seems, Application has a static launch method and an instance level start method.
In launch method we have to call start somehow.
Here is one approach how to solve it.
- We should figure out where
launchis called. - Instantiate the class.
- Call
starton that instance.
Where we are at.
Stacktrace can be a good start to figure out which class where we are at.
new Throwable().getStackTrace()[1].getClassName();
Instance of
Throwableis not thrown! The index of1returns the caller as aStackTraceElementwhich will beHelloin our example.
Instantiation
Now, we know the name of our class. Reflection can help us to make an instance out of it.
Class.forName(className).getDeclaredConstructor().newInstance();
Call start method
As we get the instance, and cast it to Application. Thanks for dynamic binding,
called start method is the one that we implemented in the child class.
Put together
String className = new Throwable().getStackTrace()[1].getClassName();
Application app;
app = (Application) Class.forName(className).getDeclaredConstructor().newInstance();
app.start();
Java 13 doc : Throwable
Java 13 doc : StackTraceElement
Java 13 doc : Class
Stacktrace and reflection can be handy many times, as we saw here as well!
Code can be found: https://github.com/torokmark/do-you-know-java