Suppose I have a method like this
public void readAndInitialize(StringReader reader, Class className)
{
// Here, I want to to something like this -
// obj = new (object of the specified className)
obj.readAndInitialize(reader);
}
How to do this in Java?
While everyone is quick to point out
Class.forName("com.myorg.MyClass");and the relatednewInstance()method, it is important to remember that it will only call a default constructor taking no parameters.If you find that you need to call a particular constructor of the class, you need to use reflections to find the correct constructor, and then call it.
lists all constructors, and a tutorial is available here.
Once you have found the desired constructor, you can call it like so
which is again, from the tutorial about reflection.