如何基于Java中的接口对象获取实现类名称 [英] How can I get the implementation class name based on the interface object in Java
本文介绍了如何基于Java中的接口对象获取实现类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的接口对象获取实现类名称-有什么方法可以做到这一点?
I want to get the implementation class name from my interface object — is there any way to do this?
我知道我可以使用instanceof
来检查实现对象,但是在我的应用程序中,有将近20到30个实现相同接口的类可以重写一个特定的方法.
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.
我想弄清楚它将要调用哪个特定方法.
I want to figure out which particular method it is going to call.
推荐答案
只需使用object.getClass()
-它会返回用于实现接口的运行时类:
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());
}
}
这篇关于如何基于Java中的接口对象获取实现类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文