0

I'm trying to get the name of a type (which is an interface) that is instantiated within a class but the available methods I've tried do not return the actual name of the type.

Example:

To get the name I would do:

class Test {

    void test(Object o) {
        System.out.println(o.getClass());
    }

}

Taking the java.lang.Runnable interface for example:

...
test(new Runnable() {});

Would print out something like class test.Test$2, I've tried other methods in the Class class but they just print out null or test.Test. How would I be able to get class java.lang.Runnable from it?

Thanks!

4

2 回答 2

1

对于内部匿名类,您可以执行以下操作:

void test(Object o) {
    if(o.getClass().isAnonymousClass()) {
      System.out.println(o.getClass().getInterfaces()[0].getName());
    } else {
      System.out.println(o.getClass().getName());
    }        
}
于 2014-04-11T16:33:16.577 回答
0

您可以通过简单地检查来做到这一点instanceof

void test(Object o) {
    System.out.println(o instanceof Runnable);
}

true如果对象实现了 Runnable 接口,这将打印出来。

如果您想要一个更动态的解决方案(例如,如果您想打印 Object 的所有接口o),您必须执行以下操作:

void test(Object o) {
    for (Class i : o.getClass().getInterfaces()) {
        System.out.println(i.getName());
    }
}
于 2014-04-11T17:04:37.937 回答