简体   繁体   English

如何迭代java类并使用hashmap选择正确的方法?

[英]How to iterate over a java class and use a hashmap to choose right method?

Java noob here, i have a program that i want to iterate the number of plugins that has been added in another file, then as long as it's a prefix and postfix calculator i want to check if the symbol in the stack for example is '+' so find Addition class that extended from Operator class and then call doAction(stack.pop(), stack.pop()) , it's because i want to add unlimited methods for calculating more symbols i tried to use reflection but i couldn't understand how to loop over between names to let the program choose the right method Java noob在这里,我有一个程序,我想迭代已经添加到另一个文件中的插件的数量,然后只要它是一个前缀和后缀计算器,我想检查堆栈中的符号是否是'+ '所以找到从Operator类扩展然后调用doAction(stack.pop(),stack.pop())的Addition类,这是因为我想添加无限的方法来计算更多符号我尝试使用反射但我不能了解如何在名称之间循环以让程序选择正确的方法

public class Operator {
    public int doAction(int op1, int op2) {
        return 0;
    }

    public String getOperator(String sign) {
        return null;
    }

    public String setOperator() {
        return null;
    }


}

class Plus extends Operator {
    public int doAction(int op1, int op2) {
        return op1 + op2;
    }

    public String setOperator() {
        return "+";
    }

    public String getOperator(String sign) {
        if (sign.equals("+")) {
            return "+";
        } else {
            return null;
        }
    }
}

class Minus extends Operator {
    public int doAction(int op1, int op2) {
        return op1 - op2;
    }

    public String setOperator() {
        return "-";
    }

    public String getOperator(String sign) {
        if (sign.equals("-")) {
            return "-";
        } else {
            return null;
        }
    }
}

By reading your requirement I would suggest to use Factory or Abstract Factory design pattern. 通过阅读您的要求,我建议使用Factory或Abstract Factory设计模式。 Basically you want to execute particular class's method based on your parameter. 基本上你想根据你的参数执行特定类的方法。 You can create factory class which return your desired class based on parameter you passed and it will do your work. 您可以创建工厂类,根据您传递的参数返回所需的类,它将完成您的工作。 for reference 以供参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM