简体   繁体   中英

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

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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