如何在Java中通过接口对象获取实现类名称

18

我想从我的接口对象中获取实现类的名称 — 有没有什么方法可以做到这一点?

我知道可以使用instanceof检查实现对象,但在我的应用程序中,有近20至30个类实现了相同的接口以覆盖一个特定的方法。

我想弄清楚它将调用哪个特定的方法。


3
为什么你需要知道呢?抽象的重点不就是使得具体类型变得不那么重要吗? - Holloway
你能具体说明你想做什么吗?可以提供一个代码示例吗?这样比较容易理解。 - Rafael Winterhalter
这听起来像是一个X->Y问题。你能解释一下找出特定方法背后的目的吗? - Sergey Kalinichenko
yourInstance.getClass().getName() - Suresh Atta
你应该先阅读这个:http://en.wikipedia.org/wiki/Reflection_(computer_programming) - tudoricc
2个回答

17

只需使用object.getClass() - 它将返回实现您接口的运行时类:

public class Test {

  public interface MyInterface { }
  static class AClass implements MyInterface { }

  public static void main(String[] args) {
      MyInterface object = new AClass();
      System.out.println(object.getClass());
  }
}

1
谢谢,两个答案都很完美。 - Veera
@Manuel 这适用于方法吗?我目前正在尝试查找Java中调用方法的位置? - Bionix1441
提出一个新问题。(简短回答:您可能需要使用异常) - Manuel

3
一个简单的 getClass() 在对象上的调用就可以工作。
示例:
public class SquaresProblem implements MyInterface {

public static void main(String[] args) {
    MyInterface myi = new SquaresProblem();
    System.out.println(myi.getClass()); // use getClass().getName() to get just the name
    SomeOtherClass.printPassedClassname(myi);
}

@Override
public void someMethod() {
    System.out.println("in SquaresProblem");
}

}

interface MyInterface {
    public void someMethod();
}

class SomeOtherClass {
    public static void printPassedClassname(MyInterface myi) {
        System.out.println("SomeOtherClass : ");
        System.out.println(myi.getClass()); // use getClass().getName() to get just the name
    }
}

输出:

class SquaresProblem --> class name
SomeOtherClass : 
class SquaresProblem --> class name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接