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

标签 java dynamic reflection

我在我的 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实际上就是我想要一种动态进行类型转换的地方。此转换必须找到一种方法来调用 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/

相关文章:

java - 是否可以限制切换仅在 kotlin/JAVA 中使用特定情况?

Java ArrayList 在自定义条件下删除重复项

asp.net-mvc-3 - 为什么 WebGrid 在格式化时使用动态?

C - 动态创建字符串数组(malloc)

c# - 从集合中通用创建逗号分隔的字符串列表

java - Spring 与 Java 反射

java - 在 JUnit 5 中参数化类和测试

java - Java中将时间分成相等的间隔

java - 为动态添加的 View 设置 OnClickListeners

scala - 如何使用 scala 宏创建函数对象(创建 Map[String, (T) => T])