代码之家  ›  专栏  ›  技术社区  ›  Sam Washburn

公共使用的向量中的私有类

  •  1
  • Sam Washburn  · 技术社区  · 15 年前

    在爪哇,当引用一个私有类时会发生什么? Vector 从课堂外?

    例子:

    public class A {
      private class B {}
      public Vector<B> vector = new Vector<B>();
    
      public A() {
        vector.add(new B());
      }
    }
    
    public class C {
      public C() {
        A a = new A();
        a.vector.get(0); // <- What does this return?
      }
    }
    
    3 回复  |  直到 9 年前
        1
  •  1
  •   dcp    15 年前

    您可以尝试以下代码:

    public static void main(String[] args) {
        A a = new A();
        Object o = a.vector.get(0); // <- What does this return?
        System.out.println(o.getClass());
    }
    

    这个阶级是A$B,所以它知道B是A的内部阶级。

    但是您不能访问b的任何成员。例如,如果您将class a更改为:

    public class A {
      private class B {
          public int x;
      }
      public Vector<B> vector = new Vector<B>();
    
      public A() {
        vector.add(new B());
        vector.get(0).x = 10;
      }
    }
    

    您仍然无法执行此操作:

    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.vector.get(0).x); // this won't compile
    }
    

    它会说 the type A.B is not visible .

        2
  •  1
  •   Alexander Pogrebnyak    15 年前

    它返回对A$B类型对象的引用。

    您可以将其分配给 Object 参考文献,例如

    Object o = a.vector.get( 0 );
    

    甚至可以使用反射来研究 o .

    只是一般性的提醒,请使用 java.util.ArrayList 而不是矢量。

        3
  •  1
  •   DaveJohnston    15 年前

    It will return an object of type A.B However you cannot do anything with it really because you will not be able to assign it to a variable or call any methods on it. 如果你这样做:

    System.out.println(a.vector.get(0));
    

    你会得到如下信息:

    A$B@42e816