【发布时间】:2013-04-07 16:13:45
【问题描述】:
我在我的 WebApp 中使用了一些 Reflexion。我想做的是在做类型案例之后动态调用一个方法——这在编译时也不知道
这是我的代码结构:
Controller (Interface with one method called 'execute()')
|
|
\|/
BaseController (Abstract Class with 1 abstr method called 'execute()')
/ \
/ _\|
/ GetCarController extends BaseController
|/_
AddCarController extends BaseController
现在我有了使用上述结构的代码:
BaseController baseContr;
Properties prop = new Properties();
prop.load("some inputstream to config.properties");
Constructor cons = Class.forName( prop.getProperty( keyProperty ) ).
getConstructor( Class.forName( prop.getProperty( keyProperty ) ).getClass() );// keyProperty is some input string from user
( ( XXXXXX )cons.newInstance ( new Car(....) ) ).execute();
您看到XXXXXX 实际上是我想要一种动态放置类型转换的方法。此强制转换必须找到在 AddCarController 或 GetCarController 中调用 execute() 方法的方法
我不想直接使用 BaseController 的任何一个实现来调用方法,而是有一种方法可以根据 prop.getProperty(keyProperty) 给出的内容进行转换...
【问题讨论】:
-
你为什么不只是投射到界面?一旦你构建了实例,你就知道它实现了接口,你可以调用 execute,对吧?
-
“它不起作用”是永远、永远、永远足够的信息。接口中没有实现。接口的全部意义在于为调用者提供一些可以在不知道实现的情况下调用的东西。它真的会起作用。
-
如果我有这样的事情:
InterfaceLevel interf = newInstanceOfImplementation; interf.executeMethodInImplementation()不能根据多态性规则工作。因为编译器必须知道在哪里可以找到实现类的方法 -
你错了。编译并且工作得很好。编译器完全了解
InstanceOfImplementation。看我的回答。 -
@kholofelo:不,确实没有,假设接口包含您要调用的方法的声明。我认为您误解了 Java 中一般的多态性和特定的接口是如何工作的。
标签: java dynamic reflection