是否可以使用 Java 反射创建内部类的实例? [英] Is it possible to create an instance of inner class using Java Reflection?

查看:28
本文介绍了是否可以使用 Java 反射创建内部类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码示例:

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

是否可以创建类 Bar 的新实例并为其命名?我尝试使用:

Is it possible to create new instance of class Bar giving its name? I tried to use:

Class c = Class.forName("Foo$Bar")

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

it finds the class, but when i use c.newInstance() it throws InstantiationException.

推荐答案

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

You need to jump through a few hoops to do this. First, you need to use Class.getConstructor() to find the Constructor object you want to invoke:

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

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.

然后你使用 Constructor.newInstance():

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

If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance

这篇关于是否可以使用 Java 反射创建内部类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆