dimanche 2 août 2015

force sub-classes to do something when they are being loaded

Suppose I want to have an abstract class like this:

public abstract Operator {

    public int[] operands;

    public Operator(int[] operands) {
        this.operands = operands;
    }

    public abstract int getOperatorResult();
}

And some operators to extend from it like:

public class Add extends Operator {

    public Add(int[] operands) {
        super(operands);
    }

    public int getOperatorResult() {
        return operands[0] + operands[1];
    }
}

And an OperatorCreator which gets an expression like "1+1" and returns the appropriate Operator's sub-class(in this case Add):

public class OperatorCreator {

    public static Operator getInstance(String expr) {
        ...
    }
}

The main problem: And I want to let others to design their own operators by extending Operator class. And use their operators polymorphically. something like this:

public class Main {

    public static void main(String[] args) {
        Operator op = OperatorCreator.getInstance("1-2");
        System.out.println(op.getOperatorResult());
    }
}

Suppose that OperatorCreator knows where .class files for Operator's sub-classes are located and uses reflection to load these sub-classes at run time. But OperatorCreator has to know one more thing: It also has to know the operator symbol for these sub-classes to return an Add object when "1+1" is given for example. So any Operator's sub-class can have a static method: "getSymbol" which returns the operator's symbol. But there is a problem. If someone extends Operator and doesn't provide "static getSymbol" her code will compile successfully without providing a mechanism for OperatorCreator to know the symbol of her new Operator's sub-class and it causes run-time problems. And I don't want to make getSymbol an abstract method of Operator to force sub-classes to implement it because I don't want to make an instance of sub-class in order to get it's symbol. How can I force sub-classes to register their symbol when they are being loaded?





Aucun commentaire:

Enregistrer un commentaire