简体   繁体   English

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

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

I want to get the implementation class name from my interface object — is there any way to do this?我想从我的接口对象中获取实现类名称——有什么办法可以做到这一点吗?

I know I can use instanceof to check the implementation object, but in my application there are nearly 20 to 30 classes implementing the same interface to override one particular method.我知道我可以使用instanceof来检查实现对象,但是在我的应用程序中,有将近 20 到 30 个类实现了相同的接口来覆盖一个特定的方法。

I want to figure out which particular method it is going to call.我想弄清楚它将调用哪个特定方法。

Just use object.getClass() - it will return the runtime class used implementing your interface:只需使用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());
  }
}

A simple getClass() on the Object would work.对象上的简单getClass()将起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM