lundi 12 décembre 2016

most efficient way calling a specific method by key

I have algorithm that give me an Integer. Based on this Integer, i want to call a method. Every Integer is unique (like a primary key in a database) and has 1 method to call. Every method returns the same datatype. The methods are all in the same class and get called in this class.

After hours of searching, i only get this 2 solutions, but i don't know which is the "better"? (running time, resources)

switch solution: first idea, but feels not very good

switch (code) {
    case 1:
        nextOperation = doMethod1();
        break;

    case 2:
        nextOperation = doMethod2();
        break;

    //many more cases...

    default:
        break;
    }

reflection solution: maybe bad running time(?)

    try{
        String methodName = "doMethod" + Integer.toString(operation.getOperationCode()); 
        //operation.getOperationCode() same like code in switch solution
        Method method = this.class.getDeclaredMethod(methodName, parametertype);
        method.invoke(nextOperation, parameter);
    }
    catch (Exception e){
        LogReport.writeLog(e.toString()); //own Log-Report filewriter
    }

Is there maybe a better way for my problem or other solutions? If you can give me a little hint, i would be very glad.





Aucun commentaire:

Enregistrer un commentaire