Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - Enclosing class vs Declaring class

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

I thought it may be to do with a subclass of the outer class instantiating an inner class that was not declared as static, but I wasn't able to get a difference that way:

public class Main {
  private static class StaticInnerClass {

  }

  private class MemberInnerClass {

  }

  private static class ChildClass extends Main {

  }

  public MemberInnerClass getMemberInnerClassInstance() {
    return new MemberInnerClass();
  }

  public static void main(String[] args) {
    System.out.println( StaticInnerClass.class.getDeclaringClass() );
    System.out.println( StaticInnerClass.class.getEnclosingClass() );
    System.out.println( MemberInnerClass.class.getDeclaringClass() );
    System.out.println( MemberInnerClass.class.getEnclosingClass() );
    System.out.println( new ChildClass().getMemberInnerClassInstance().getClass().getEnclosingClass() );
    System.out.println( new ChildClass().getMemberInnerClassInstance().getClass().getDeclaringClass() );
  }
}

Output:

class Main
class Main
class Main
class Main
class Main
class Main
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...