我清楚oop的多态性和继承概念,但是我处于需要知道实现类的情况。例如:
public CommonReadRepository<?> getReadRepository(String tableName) {
if (tableName == null)
return null;
switch (tableName) {
case "order":
return orderRepository;
...
}
return null;
}
接口(interface)orderRepository
扩展了CommonReadRepository
,并且由于我的需求,我需要访问orderRepository中定义的函数。
CommonReadRepository<?> repository=getReadRepository("order");
有什么方法可以检查CommonReadRepository
的实现(子)类或接口(interface)吗?
当然,我总是可以做这样的事情:
if(tableName=="order")
return (OrderRepository)CommonReadRepository<?>;
我尝试调试 getReadRepository("order")
,但它给了我一个 JdkDynamicAopProxy
实例,我不确定它是如何工作的。
if(interface is instanceof xyz class) i do not want to use it because i have 100 of classes and i want to keep it as a last resort... or in other words i don't know about xyz class
谢谢
最佳答案
以下是检查返回的对象是否是指定类的实例的一种方法:
CommonReadRepository<?> repository=getReadRepository("order");
if(repository instanceof WhatEverSubclass) {
// do something
}
但是使用这种方法并不是 OOP 应该如何完成的。如果您的类都实现相同的接口(interface),为什么不定义一个通用方法,然后在所有子类中使用该方法,但每次都以不同的方式实现它。
关于java - 如何检索父接口(interface)的实现类/接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555246/