Enclosing class vs Declaring class

后端 未结 1 1953
误落风尘
误落风尘 2020-12-09 15:58

Are there any circumstances in which Class.getDeclaringClass could give a different result from Class.getEnclosingClass?

I thought it may b

相关标签:
1条回答
  • 2020-12-09 16:44

    Found here http://kickjava.com/1139.htm#ixzz1mv2nEWg7:

    "The subtilty with getDeclaringClass is that anonymous inner classes are not counted as member of a class in the Java Language Specification whereas named inner classes are. Therefore this method returns null for an anonymous class. The alternative method getEnclosingClass works for both anonymous and named classes."

    For example:

    public class Test {
        public static void main(String[] args) {
            new Object() {
                public void test() {
                    System.out.println(this.getClass().getDeclaringClass()); //null
                    System.out.println(this.getClass().getEnclosingClass()); //not null
                }
            }.test();
        }
    }
    

    The same holds for non-anonymous classes in a method scope:

    class Foo {
      Class<?> bar() throws NoSuchFieldException {
        class Bar<S> { }
        return Bar.class;
      }
    
      static void main(String[] args) throws NoSuchFieldException {
        System.out.println(new Foo<Void>().bar().getDeclaringClass()); // null
        System.out.println(new Foo<Void>().bar().getEnclosinglass()); // Foo
      }
    }
    
    0 讨论(0)
提交回复
热议问题