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

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

    Did you try using getEnclosingClass():

    Returns the immediately enclosing class of the underlying class. If the underlying class is a top level class this method returns null.

    Outer.class.equals(object.getClass().getEnclosingClass())
    

    Getting the correct enclosing class of the object , IMHO is not so easy . Read this.

    Somewhat of a hack would be :

    object.getClass().getName().contains("Outer$");
    

提交回复
热议问题