gpt4 book ai didi

java - 在 Java 中动态转换和调用

转载 作者:行者123 更新时间:2023-11-30 06:25:11 26 4
gpt4 key购买 nike

我在我的 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 的地方实际上是我想要一种动态类型转换的方法。此转换必须找到一种方法来调用 AddCarControllerGetCarController 中的 execute() 方法 我不想直接使用 BaseController 的任何一个实现来调用方法,而是有一种方法可以根据 prop.getProperty(keyProperty) 给...

最佳答案

我认为您混淆了多态性的工作原理。如果您需要知道要转换到的确切类,那将完全破坏多态性的全部目的。

即使您转换为 BaseController - 或接口(interface),如 Jon Skeet 所指出的,实际上更正确 -,该实例仍将是 AddCarControllerGetCarController实例,在这个实例中调用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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com