InstantiationException with newInstance() when creating an object of an inner class

Hi all
I am trying to use Class.forName().newInstance() to create objects from names.
The class is created ok (no ClassNotFoundException) but the newInstance() fails
with InstantiationException.

The class is a non-static non-abstract inner class of an inner class with a simple constructor.

          String className = "com.menatwork.gui$MultiDialog$anotherDialog";
          Class clazz = Class.forName(className);
          // fails here
          Object ob = clazz.newInstance();

Is there a problem creating objects from inner classes or am I barking up the wrong tree?

Thanks

Rich
richard_fairallAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
depending on what constructors you have defined, you could try something like:

Constructors[] ctors = clazz.getDeclaredConstructors();
Object obj = ctors[0].newInstance(new Object[] {this});
0
 
objectsCommented:
what does your inner class look like?
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> The class is a non-static non-abstract inner class of an inner class with a simple constructor.

Are you sure about each one of that?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Mayank SAssociate Director - Product EngineeringCommented:
Since its a non-static inner class, I guess you would need an object of the enclosing class to instantiate it. You can't instantiate an object of a non-static inner class without having an object of the outer class.
0
 
objectsCommented:
> I guess you would need an object of the enclosing class to instantiate it.

Thats correct, and the reason for passing 'this' to the ctor in the code I posted above.
0
 
richard_fairallAuthor Commented:
Thanks objects,
So fast - unbelievable.
I dont know what country you are in, or what time it is there, but thanks for being up!
That worked a treat.

Rich
0
 
objectsCommented:
Sydney, Australia.
And it's about beer o'clock here, so you got me jit :)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Assuming you are using that code in the enclosing class ;) good that it worked.
0
All Courses

From novice to tech pro — start learning today.