How can I get the implementation class name based on the interface object in Java

这一生的挚爱 提交于 2019-11-30 19:44:12

Just use object.getClass() - it will return the runtime class used implementing your interface:

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());
  }
}

A simple getClass() on the Object would work.

example :

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
    }
}

O/P :

class SquaresProblem --> class name
SomeOtherClass : 
class SquaresProblem --> class name
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!