Instantiating an inner class

前端 未结 4 1475
逝去的感伤
逝去的感伤 2020-12-29 08:51

I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this:

public static  List<         


        
相关标签:
4条回答
  • 2020-12-29 09:23

    In Jmockit 1.41, use this:

    ConstructorReflection.newInstance

    0 讨论(0)
  • 2020-12-29 09:29

    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() {}
        }
    }
    
    0 讨论(0)
  • 2020-12-29 09:45

    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;
         }
    
    0 讨论(0)
  • 2020-12-29 09:45

    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?

    0 讨论(0)
提交回复
热议问题