![](/img/trans.png)
[英]How can I get the type of the implementation class stored in the variable declared in the interface type by Java reflection?
[英]How can I get the implementation class name based on the interface object in Java
我想从我的接口对象中获取实现类名称——有什么办法可以做到这一点吗?
我知道我可以使用instanceof
来检查实现对象,但是在我的应用程序中,有将近 20 到 30 个类实现了相同的接口来覆盖一个特定的方法。
我想弄清楚它将调用哪个特定方法。
只需使用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());
}
}
对象上的简单getClass()
将起作用。
例子 :
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
}
}
开/关:
class SquaresProblem --> class name
SomeOtherClass :
class SquaresProblem --> class name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.