[英]Public constructor, can not create instance
Have this code: 有此代码:
public final class A {
public final class B {
}
public A(B b) {
}
}
Problem: 问题:
A
without an instance of B
. B
的实例,就无法创建A
的实例。 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.