Reputation:
I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this:
public static <A extends Foo> List<A> getFooList(Class<A> clazz) {
List<A> returnValue = new ArrayList<A>();
for(int i=0; i < 5; i++) {
A object = clazz.newInstance();
returnValue.add(object);
}
return returnValue;
}
The problem is, that if clazz
is an inner class such as Foo.Bar.class
, then the newInstance()
method will not work even if Bar
would be public, as it will throw a java.lang.InstantiationException
.
Is there a way to dynamically instantiate inner classes?
Upvotes: 14
Views: 10473
Reputation: 1640
Something more generic:
public static <T> T createInstance(final Class<T> clazz) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
T instanceToReturn = null;
Class< ? > enclosingClass = clazz.getEnclosingClass();
if (enclosingClass != null) {
Object instanceOfEnclosingClass = createInstance(enclosingClass);
Constructor<T> ctor = clazz.getConstructor(enclosingClass);
if (ctor != null) {
instanceToReturn = ctor.newInstance(instanceOfEnclosingClass);
}
} else {
instanceToReturn = clazz.newInstance();
}
return instanceToReturn;
}
Upvotes: 5
Reputation: 9692
This exception will be thrown only if clazz represents either an abstract class or an interface. Are you sure you're passing a Class object that represents a concrete class?
Upvotes: 0
Reputation: 1499950
If it's genuinely an inner class instead of a nested (static) class, there's an implicit constructor parameter, which is the reference to the instance of the outer class. You can't use Class.newInstance
at that stage - you have to get the appropriate constructor. Here's an example:
import java.lang.reflect.*;
class Test
{
public static void main(String[] args) throws Exception
{
Class<Outer.Inner> clazz = Outer.Inner.class;
Constructor<Outer.Inner> ctor = clazz.getConstructor(Outer.class);
Outer outer = new Outer();
Outer.Inner instance = ctor.newInstance(outer);
}
}
class Outer
{
class Inner
{
// getConstructor only returns a public constructor. If you need
// non-public ones, use getDeclaredConstructors
public Inner() {}
}
}
Upvotes: 27