简体   繁体   English

公共构造函数,无法创建实例

[英]Public constructor, can not create instance

Have this code: 有此代码:

public final class A {
    public final class B {
    }
    public A(B b) {
    }
}

Problem: 问题:

  1. You can not create an Instance of A without an instance of B . 没有B的实例,就无法创建A的实例。
  2. You can not create an Instance of B without an instance of A . 您不能创建的实例, B没有实例A

Without changing the code and without reflection, how to create an Instance of A ? 在不更改代码且没有反射的情况下,如何创建A的实例?

You can use null : 您可以使用null

new A(null);

Once you have an A object, you can create a B object too: 一旦有了A对象,就可以创建一个B对象:

A a = new A(null);
B b = a.new B();

To expand on MC Emperor's answer, you can also create an instance of A with non null instance of B : 为了扩展MC Emperor的答案,您还可以创建A实例和B非null实例:

A a1 = new A(null);
B b1 = a1.new B();
A a2 = new A(b1);

and in a one liner: 在一个班轮里:

A a = new A(new A(null).new B());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM