是否可以使用Java Reflection创建嵌套类的实例?

kar*_*s7e 34 java reflection inner-classes

代码示例:

public class Foo
{
    public class Bar
    {
         public void printMesg(String body)
         {
             System.out.println(body);
         }
    }
    public static void main(String[] args)
    {
         // Creating new instance of 'Bar' using Class.forname - how?
    }        
}
Run Code Online (Sandbox Code Playgroud)

是否可以创建类Bar的新实例给它的名字?我试着用:

Class c = Class.forName("Foo$Bar")
Run Code Online (Sandbox Code Playgroud)

它找到了类,但是当我使用c.newInstance()时它会抛出InstantiationException.

ska*_*man 54

你需要跳过几个箍才能做到这一点.首先,您需要使用Class.getConstructor()来查找Constructor要调用的对象:

返回一个Constructor对象,该对象反映此Class对象所表示的类的指定公共构造函数.parameterTypes参数是一个Class对象数组,它按声明的顺序标识构造函数的形式参数类型.如果此Class对象表示在非静态上下文中声明的内部类,则形式参数类型包括显式封闭实例作为第一个参数.

然后使用Constructor.newInstance():

如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数需要是封闭的实例


Bal*_*usC 25

如果不首先构造父类,确实不能构造内部类.它不能存在于父类之外.在进行反射时,您必须传递父类的实例.嵌套类是static和它们可以独立于父类使用,因此也可以在进行反射时使用.

这是一个展示所有东西的SSCCE.

package mypackage;

import java.lang.reflect.Modifier;

public class Parent {

    public static class Nested {
        public Nested() {
            System.out.println("Nested constructed");
        }
    }

    public class Inner {
        public Inner() {
            System.out.println("Inner constructed");
        }
    }

    public static void main(String... args) throws Exception {
        // Construct nested class the normal way:
        Nested nested = new Nested();

        // Construct inner class the normal way:
        Inner inner = new Parent().new Inner();

        // Construct nested class by reflection:
        Class.forName("mypackage.Parent$Nested").newInstance();

        // Construct inner class by reflection:
        Object parent = Class.forName("mypackage.Parent").newInstance();
        for (Class<?> cls : parent.getClass().getDeclaredClasses()) {
            if (!Modifier.isStatic(cls.getModifiers())) {
                // This is an inner class. Pass the parent class in.
                cls.getDeclaredConstructor(new Class[] { parent.getClass() }).newInstance(new Object[] { parent });
            } else {
                // This is a nested class. You can also use it here as follows:
                cls.getDeclaredConstructor(new Class[] {}).newInstance(new Object[] {});
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该产生

Nested constructed
Inner constructed
Nested constructed
Inner constructed
Nested constructed

  • 优秀而完整的榜样! (2认同)

mer*_*ike 7

快速而脏的代码:

Foo.Bar.class.getConstructors()[0].newInstance(new Foo());
Run Code Online (Sandbox Code Playgroud)

说明:您必须告诉Bar其封闭的Foo.

  • 嗯,我的回答是假设班级不是静态的?如果该类是隐形OP将获得IllegalAccessException,而不是InstantiationException ... (2认同)