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

孤街醉人 提交于 2019-12-09 05:08:55

问题


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

回答1:


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.




回答2:


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.




回答3:


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$");



回答4:


you could always:

getClass().getName()

and do a String comparison.

EDIT : to account for inheritance (among inner classes? who would do that?!) you could always loop through getSuperclass() and check for them as well, and even go after implemented interfaces.




回答5:


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




回答6:


I was googling for finding out better answers, to find out that there are none out there.

Here is what I have which works pretty well:

    public static boolean isStatic(Class klass) {
            return Modifier.isStatic(klass.getModifiers());
    }

    /**
     * Non static inner class
     */
    public static boolean isInnerclass(Class klass) {
            return klass.getDeclaringClass() != null && !isStatic(klass);
    }

Will return true for local inner classes. isMemberClass and others do not work for this purpose.



来源:https://stackoverflow.com/questions/17468198/java-how-to-check-if-an-object-is-an-instance-of-a-non-static-inner-class-rega

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!