java - 是否可以使用 Java 反射创建内部类的实例?

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

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

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

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

最佳答案

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

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 - 是否可以使用 Java 反射创建内部类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2097982/

相关文章:

java - 在 Java 中美化 GraphQL 查询字符串

java - 如何使用 System.out.format() 在 Java 中的一行上显示多个项目?

java - 如何生成斐波那契数列?

Java 8 Stream - 在下一行完成映射后是否可以使用对象?

c# - 如何通过泛型获取接口(interface)的具体实现?

c++ - 模板类内部类的映射迭代器的正确语法?

java - 需要 ContentProvider 来访问 SharedPreferences

c# - 如何获取 C# 中泛型约束的有效类型对象?

java - 实现 toString() 时使用反射有意义吗?

scala - 在 asInstanceOf 中引用嵌套类