kmecpp
kmecpp

Reputation: 2479

How to get the original class from anonymous class? Java

I can't figure out how to get the original abstract class or interface where an anonymous inner class is defined.

For example:

public static void main(String[] args) {
    Object obj = new Runnable() {

        @Override
        public void run() {
        }
    };

    System.out.println(obj.getClass());
    System.out.println(obj.getClass().getSuperclass()); //Works for abstract classes only
}

Output:

class my.package.MyClass$1
class java.lang.Object

How can I get the original class? (Runnable.class in this case)

Upvotes: 2

Views: 2123

Answers (3)

kmecpp
kmecpp

Reputation: 2479

Thanks for the help! No one really answered my question fully, so I decided to combine the different answers to get this comprehensive solution.

public static Class<?> getOriginalClass(Object obj) {
    Class<?> cls = obj.getClass();
    if (cls.isAnonymousClass()) {
        return cls.getInterfaces().length == 0 ? cls.getSuperclass() : cls.getInterfaces()[0];
    } else {
        return cls;
    }
}

Shortened:

public static Class<?> getOriginalClass(Object obj) {
    Class<?> cls = obj.getClass();
    return cls.isAnonymousClass()
            ? cls.getInterfaces().length == 0 ? cls.getSuperclass() : cls.getInterfaces()[0]
            : cls;
}

Upvotes: 4

Malphrush
Malphrush

Reputation: 338

As others have mentioned runnable is an interface, so you can't use the getClass method to get its name. You can however do this:

System.out.println(obj.getClass().getInterfaces()[0].getName())

Notice getInterfaces returns an array so if you were implementing more than one you'd have to loop through it with a for loop.

Upvotes: 1

Denis
Denis

Reputation: 2140

What you are doing is correct to get the superclass. But Runnable is an interface that's why it isn't working. Check this answer on how to get all interfaces: Get all interfaces

Upvotes: 1

Related Questions