Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中用反射实例化内部类?_Java_Reflection_Instantiationexception - Fatal编程技术网

如何在Java中用反射实例化内部类?

如何在Java中用反射实例化内部类?,java,reflection,instantiationexception,Java,Reflection,Instantiationexception,我尝试实例化以下Java代码中定义的内部类: public class Mother { public class Child { public void doStuff() { // ... } } } 当我试图得到这样一个孩子的例子时 Class<?> clazz= Class.forName("com.mycompany.Mother$Child"); Child c = cl

我尝试实例化以下Java代码中定义的内部类:

 public class Mother {
      public class Child {
          public void doStuff() {
              // ...
          }
      }
 }
当我试图得到这样一个孩子的例子时

 Class<?> clazz= Class.forName("com.mycompany.Mother$Child");
 Child c = clazz.newInstance();
我缺少什么?

有一个额外的“隐藏”参数,它是封闭类的实例。您需要使用获取构造函数,然后提供封闭类的实例作为参数。例如:

// All exception handling omitted!
Class<?> enclosingClass = Class.forName("com.mycompany.Mother");
Object enclosingInstance = enclosingClass.newInstance();

Class<?> innerClass = Class.forName("com.mycompany.Mother$Child");
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);

Object innerInstance = ctor.newInstance(enclosingInstance);

这段代码创建内部类实例

  Class childClass = Child.class;
  String motherClassName = childClass.getCanonicalName().subSequence(0, childClass.getCanonicalName().length() - childClass.getSimpleName().length() - 1).toString();
  Class motherClassType = Class.forName(motherClassName) ;
  Mother mother = motherClassType.newInstance()
  Child child = childClass.getConstructor(new Class[]{motherClassType}).newInstance(new Object[]{mother});

嗯,你的内心世界不是静止的。。。这是故意的吗?来自C#背景可能是?;)感谢您提出“静态”的想法!事实上,使用静态嵌套类而不是内部类使我的生活更轻松;这与C#不同,C#默认情况下所有内部类都是“静态”的,并且可以在没有父实例的情况下实例化。我相信真正的问题是OP并不意味着类一开始就不是静态的,但我可能是mistaken@fge:可能。我将在回答中提到这一点。另外一个问题是,如果内部类不是公共类,则需要调用
ctor.setAccessible(true)
,以使其工作!有趣的是,在遛狗的时候我想。。。真奇怪,乔恩有这么多答案,但我在查东西的时候很少碰到它们。然后。。。正在研究我的答案。。。是的。你的回答帮我回答了一些棘手的问题Y:谢谢!现在有了内部实例,您将如何调用它的方法?
public class Mother {
     public static class Child {
          public void doStuff() {
              // ...
          }
     }
}
  Class childClass = Child.class;
  String motherClassName = childClass.getCanonicalName().subSequence(0, childClass.getCanonicalName().length() - childClass.getSimpleName().length() - 1).toString();
  Class motherClassType = Class.forName(motherClassName) ;
  Mother mother = motherClassType.newInstance()
  Child child = childClass.getConstructor(new Class[]{motherClassType}).newInstance(new Object[]{mother});