Java: How to check if an object is an instance of a non-static inner class, regardless of the outer object?

后端 未结 6 1166
遥遥无期
遥遥无期 2021-02-05 10:35

If I have an inner class e.g.

class Outer{
    class Inner{}
}

Is there any way to check if an arbitrary Object is an instance of

6条回答
  •  我寻月下人不归
    2021-02-05 10:58

    o instanceof Outer.Inner gives false when o is an instance of an Inner of any Outer other than the one you're calling it from.

    This doesn't happen for me - I get true for o instanceof Inner regardless of which particular enclosing instance of Outer the o belongs to:

    class Outer {
      class Inner {}
    
      void test() {
        // Inner instance that belongs to this Outer
        Inner thisInner = new Inner();
    
        // Inner instance that belongs to a different Outer
        Outer other = new Outer();
        Inner otherInner = other.new Inner();
    
        // both print true
        System.out.println(thisInner instanceof Inner);
        System.out.println(otherInner instanceof Inner);
      }
    
      public static void main(String[] args) {
        new Outer().test();
      }
    }
    

    Tested with both Java 6 and 7.

提交回复
热议问题