2

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)

kmecpp
  • 2,371
  • 1
  • 23
  • 38

3 Answers3

4

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;
}
kmecpp
  • 2,371
  • 1
  • 23
  • 38
1

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

Denis
  • 2,030
  • 1
  • 12
  • 15
1

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.

Malphrush
  • 328
  • 3
  • 12