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

后端 未结 6 1063
遥遥无期
遥遥无期 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:54

    The java.lang.Class.getEnclosingClass() method returns the immediately enclosing class of the underlying class. If this class is a top level class this method returns null.

    The following example shows the usage of java.lang.Class.getEnclosingClass() method:

    import java.lang.*;
    
    public class ClassDemo {
       // constructor
       public ClassDemo() {
    
          // class Outer as inner class for class ClassDemo
          class Outer {
    
             public void show() {
                // inner class of Class Outer
                class Inner {
    
                   public void show() {
                      System.out.print(getClass().getName() + " inner in...");
                      System.out.println(getClass().getEnclosingClass());    
                   }
                }
                System.out.print(getClass().getName() + " inner in...");
                System.out.println(getClass().getEnclosingClass());
    
                // inner class show() function
                Inner i = new Inner();
                i.show();
             }
          }
    
          // outer class show() function
          Outer o = new Outer();
          o.show();
       }
    
       public static void main(String[] args) {
         ClassDemo cls = new ClassDemo();
       }
    }
    

    Output

    ClassDemo$1Outer inner in...class ClassDemo

    ClassDemo$1Outer$1Inner inner in...class ClassDemo$1Outer

提交回复
热议问题