0

考虑一个简单的例子,我要求用户从 10 种不同的水果中选择一种水果。假设水果是,苹果,橙子,芒果,......等等,如果用户选择苹果,我调用apples(),如果他选择芒果,我调用mangoes()等等......

要选择要调用的函数,我不想使用 switch 或 if-else 语句。如何选择在运行时调用哪个函数?

注意:我使用的编程语言是 Java

4

3 回答 3

0

使用Reflection. eg:将所有函数写在一个类中;说com.sample.FruitStall 然后使用下面的代码。

String className = "com.sample.FruitStall";
String methodName = "apple"; //here you will choose desired method
Object result;
Class<?> _class;
        try {
            _class = Class.forName(className);
        } catch (Exception e) {
            e.printStackTrace();
        }
            Object[] args = new Object[1];  // To Supply arguments to function
            result = _class.invokeMethod(methodName, args);
于 2012-10-11T05:24:00.557 回答
0

使用 java Refection api在运行时调用函数。

        Class noparams[] = {};
        Class cls = Class.forName("com.test.Fruit");
        Object obj = cls.newInstance();

        //call the printIt method
        Method method = cls.getDeclaredMethod("apples", noparams);
        method.invoke(obj, null);
于 2012-10-11T05:24:32.790 回答
0

使用设计模式“命令”。 http://www.codeproject.com/Articles/186192/Command-Design-Pattern

隐藏它需要执行的操作的细节。

于 2012-10-11T05:27:56.983 回答