Sample of code:
public class Foo
{
public class Bar
{
public void printMesg(String body)
{
System.out.println(body);
}
}
public static void main(String[] args)
{
// Creating new instance of 'Bar' using Class.forname - how?
}
}
Is it possible to create new instance of class Bar giving its name? I tried to use:
Class c = Class.forName("Foo$Bar")
it finds the class, but when i use c.newInstance() it throws InstantiationException.
You need to jump through a few hoops to do this. First, you need to use Class.getConstructor() to find the Constructor
object you want to invoke:
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
And then you use Constructor.newInstance():
If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance