我在我的 Web 应用程序中使用了一些 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)
提供的内容来转换它...
最佳答案
我认为您对多态性的工作原理感到困惑。如果您需要知道要转换到的确切类,那就完全违背了多态性的全部目的。
即使您转换为 BaseController
- 或接口(interface),正如 Jon Skeet 所指出的,这实际上更正确 -,该实例仍将是 AddCarController
或GetCarController
实例,在此实例中调用 execute()
将调用 AddCarController#execute()
或 GetCarController#execute()
和从不 BaseController#execute()
。
以下是此行为的示例:
class A {
public void hello() {
System.out.println("Hello from class A");
}
}
class B extends A {
@Override
public void hello() {
System.out.println("Hello from class B");
}
}
public class Main {
/**
* @param args
* @throws OperationNotSupportedException
*/
public static void main(final String[] args) {
final A a = new B();
a.hello();
}
}
按预期打印“Hello from class B”
。
编辑:使用反射和接口(interface)的更详细示例:
class A implements I {
@Override
public void hello() {
System.out.println("Hello from class A");
}
}
class B implements I {
@Override
public void hello() {
System.out.println("Hello from class B");
}
}
interface I {
public void hello();
}
public class Main {
/**
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws OperationNotSupportedException
*/
public static void main(final String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
I i = (I) Class.forName("A").newInstance();
i.hello();
i = (I) Class.forName("B").newInstance();
i.hello();
}
}
关于java - Java 中的动态转换和调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16017023/