dimanche 7 mai 2017

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;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire