Here’s a real life example I had experienced before, and this is something that makes me ponder and question this mystery.
Before: I have no idea how to instantiate a class dynamically just by using the name of the class.
After: I looked around in someone else’s Java source code, being determined to look for something unrelated to the above, like how to do collision detection, and just accidentally came across a piece of code that answers correctly my question of how to instantiate a class dynamically.
The piece of code in question is this:
A a = (A) Class.forName("A").newInstance();
Where A is the name of a Java source file, A.java.
From here, I was not only intrigued about it, but also starting to wonder, how a Java programmer learn all of this if they were given only the Java language documentation.
How do they know where to look for in the documentation, if they are practicing Java language?
I know that novice Java programmers get some experiences from expert Java programmers, but where do the expert Java programmers learn all of this, if they at first don’t know where to look for in the documentation?
Or do they just read from page 1 to the end of the documentation, and follow along closely as much as possible, and start from there? That would take a long time to finish, and it would be an impressive feat to do.
Usually you search google for the Java docs… that send you to the Oracle website that contains it. http://docs.oracle.com/javase/7/docs/api/
On some cases only the API is necessary, but when you need a full formed example you could search for code samples or snippets, or the problem you want to solve itself (i.e. “java instantiate class dinamically”).
On the issue of the dynamic instantiation there are a lot of ClassLoader things that can be done but the most basic exemple is similar to the one you found… but there is a catch.
When you reference the A class on your code the jvm automatically loads it for you.
When you do
You will reference the A class you already have a grip of.
What you could do is create an interface that the classes you want to instantiate have to implement, like this:
And you use it from there.
But you have to remember to add the try-catch block, because the newInstance method will only know if the referenced class has a default constructor when it tries ti instantiate it at runtime, and if it doesn’t have there will be an exception.
The same goes for a exception thrown by the contructor itself, it will be encapsulated and thrown back at you.