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.
Inner classes can indeed not be constructed without constructing the parent class first. It cannot exist outside the parent class. You'll have to pass an instance of the parent class in when doing reflection. Nested classes are
static
and they can be used independently from the parent class, thus also when doing reflection.Here's an SSCCE which demonstrates all the stuff.
This should produce
Quick and dirty code:
Explanation: You must tell the Bar about its enclosing Foo.
Other answers have explained how you can to what you want to do.
But I want to suggest to you that the fact that you need to do this at all is an indication that there is something a bit wrong with your system design. I would suggest that you either need a (non-static) factory method on the enclosing class, or you need to declare the inner class as static.
Creating a (non-static) inner class instance reflectively has a "smell" of broken encapsulation.
This isn't entirely optimal, but it works for depths of inner classes and inner static classes.
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:And then you use Constructor.newInstance():
Here a answer for nested class (static inner): In my case i need to acquire the type by its fully qualified name
the '$' is crucial!
with a dot you'll get ClassNotFoundException for class "package.innerClass.outerClass". The exception is missleading :-(.