代码示例:
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/