Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 any Inner, regardless of its outer object? instanceof gives false when the objects are not Inners from the same Outer. I know a workaround is just to make Inner a static class, but I'm wondering if what I'm asking is possible.

Example:

class Outer{
    Inner inner = new Inner();
    class Inner{}

    public boolean isInner(Object o){
        return o instanceof Inner;
    }
}


Outer outer1 = new Outer();
Outer outer2 = new Outer();
boolean answer = outer1.isInner(outer2.inner); //gives false
like image 630
Navigateur Avatar asked Jul 04 '13 10:07

Navigateur


2 Answers

And what about?

public static boolean isInnerClass(Class<?> clazz) {
    return clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers());
}

The method isMemberClass() will test if the method is a member (and not an anonymous or local class) and the second condition will verify that your member class is not static.

By the way, the documentation explains the differences between local, anonymous and nested classes.

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

like image 51
LaurentG Avatar answered Oct 13 '22 05:10

LaurentG


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.

like image 40
Ian Roberts Avatar answered Oct 13 '22 05:10

Ian Roberts