From a jsp I get a string that I could use for a switch
switch(value)
case 0: method0(); break;
case 1: method1(); break;
...
or for a reflection:
c.getMethod("method"+value, parameter);
...
Which approach is more efficient?
Reflection is definitely not faster, as it has to go through additional layers.
However, using reflection for such a task would be the wrong way, as it makes the code harder to maintain and doesn't serve a real purpose which reflection is designed for.
If you have fixed number of methods and you are just lazy to type 1000 different cases, then you'd definitely use switch, because that statement is highly optimized on JVM bytecode level.
If you have an indefinite number of methods, you could use reflection (probably you don't have any other choices). Still you can speed up the process by caching the Method instances you get from getMethod().
Note that passing arguments via reflection always creates extra arrays of Classes and Objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With