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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24992959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:19:24  来源:igfitidea点击:

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

javaoverriding

提问by Veera

I want to get the implementation class name from my interface object — is there any way to do this?

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

I know I can use instanceofto 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.

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

采纳答案by Manuel

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

回答by TheLostMind

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