开发者

Get the superclass of an anonymous or inner class [closed]

It's diff开发者_JAVA百科icult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How to get the superclass of an anonymous class:

 Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println(this.getClass().getSuperclass());
    }
 };

This prints java.lang.Object. Because getClass() returns EnclosingClass$1.

System.out.println(r.getClass()); // class test.ClassTest$1
System.out.println(r.getClass().getSuperclass()); // class java.lang.Object
System.out.println(Runnable.class.isAssignableFrom(r.getClass())); // true
System.out.println(Runnable.class.isInstance(r)); // true

(All these methods are native)

So is there any way to get the superclass of the anonymous class? It seems this is known at runtime. For the above example I want to obtain Runnable. Same goes for inner classes by the way - if you define class Foo implements Runnable I don't see a way to obtain Runnable

The reason why this is important is that some frameworks may rely on getClass().getSuperclass() and it may appear that you should be careful when using anonymous and inner classes.


For this case, Runnable is an interface which can be gotten via getInterfaces. In cases where anonymous classes extend a base class getSuperclass() should work just fine.


The super class is java.lang.Object. All objects extend Object by default.

Runnable is an interface. You won't see it in the implementation hierarchy, regardless of the subject of the call (normal class, inner class, anonymous inner class).

Can you explain why you think Runnable should be visible in the implementation hierarchy?


Runnable is an interface, not a class. You will get the same result for a real class that implements Runnable (or other interface) and doesn't extend any class.

The following code will print class java.lang.Thread:

     Thread r = new Thread() {
        @Override
        public void run() {
            System.out.println(this.getClass().getSuperclass());
        }
     };
     r.start();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜