views:

803

answers:

2
+7  A: 

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() {}
    }
}
Jon Skeet
A: 

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?

Sandman