java 实例化一个内部类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/728842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:32:24  来源:igfitidea点击:

Instantiating an inner class

javainner-classes

提问by Jon Skeet

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 clazzis an inner class such as Foo.Bar.class, then the newInstance()method will not work even if Barwould be public, as it will throw a java.lang.InstantiationException.

问题是,如果clazz是一个内部类,例如Foo.Bar.class,那么newInstance()即使Bar是公开的方法也不会工作,因为它会抛出一个java.lang.InstantiationException.

Is there a way to dynamically instantiate inner classes?

有没有办法动态实例化内部类?

回答by Jon Skeet

If it's genuinely an innerclass 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.newInstanceat that stage - you have to get the appropriate constructor. Here's an example:

如果它真的是一个内部类而不是嵌套(静态)类,则有一个隐式构造函数参数,它是对外部类实例的引用。您不能Class.newInstance在那个阶段使用- 您必须获得适当的构造函数。下面是一个例子:

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() {}
    }
}

回答by pierrefevrier

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

回答by TheJeff

In Jmockit 1.41, use this:

在 Jmockit 1.41 中,使用这个:

ConstructorReflection.newInstance

构造函数反射.newInstance

回答by Sandman

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?

仅当 clazz 表示抽象类或接口时才会抛出此异常。您确定要传递代表具体类的 Class 对象吗?