Issue
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)
Solution
Thanks for the help! No one really answered my question fully though, 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;
}
Answered By - kmecpp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.