简体   繁体   English

如何实例化嵌套的私有静态类 java

[英]How do I instantiate a nested private static class java

Lets say I have some nested classes假设我有一些嵌套类

class A{
  private static class B{}
  static class C{ 
    B b;
    C(B b){
        this.b=b;
    }
    int foo(){
        return 42;
    }
  }
} 

I am trying to instantiate the private static class B by doing the following我正在尝试通过执行以下操作来实例化私有静态类 B

new A.C(new A.B())

but because B is private I'm unable to do this.但因为 B 是私人的,我无法做到这一点。 What is a way of constructing class C with a class B?用 B 类构造 C 类的方法是什么?

You can either make B non private, or provide a helper method in A to create C :您可以将B设为非私有,也可以在A提供辅助方法来创建C

class A{
  private static class B{}
  static class C{ 
    B b;
    C(B b){
        this.b=b;
    }
    int foo(){
        return 42;
    }
  }
  static createC() {
    return new C(new B());
  }
} 

So that outside of A , you can create an instance of C like this:因此,在A之外,您可以像这样创建C的实例:

A.C myc = A.create();

Note that since B is not visible outside, the constructor of C is useless, so you can make that private.请注意,由于B在外部不可见,因此C的构造函数无用,因此您可以将其设为私有。

如果您只是想进行测试并绕过断言错误,那么您可以使用 b 的空值实例化 c,然后创建一个匿名类并覆盖 foo。

new AC(null){int foo(){return 42;}}

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

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