如何根据Java中的接口对象获取实现类名称

Vee*_*era 9 java overriding

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

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

我想弄清楚它将调用哪种特定方法.

Man*_*uel 11

只需使用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());
  }
}
Run Code Online (Sandbox Code Playgroud)