简体   繁体   English

实例化内部类

[英]Instantiating an inner class

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 . 问题是,如果clazz是一个内部类,如Foo.Bar.class ,那么即使Bar是公共的, newInstance()方法也不会工作,因为它会抛出一个java.lang.InstantiationException

Is there a way to dynamically instantiate inner classes? 有没有办法动态实例化内部类?

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. 你不能在那个阶段使用Class.newInstance - 你必须得到适当的构造函数。 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() {}
    }
}

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;
     }

In Jmockit 1.41, use this: 在Jmockit 1.41中,使用:

ConstructorReflection.newInstance ConstructorReflection.newInstance

This exception will be thrown only if clazz represents either an abstract class or an interface. 仅当clazz表示抽象类或接口时,才会抛出此异常。 Are you sure you're passing a Class object that represents a concrete class? 您确定要传递代表具体类的Class对象吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM