1

I got an application which should call different methods, based on the params' input. My idea until now is basically, that I create a Switch and call the methods separately by its case. Example:

switch (methodName)
{
    case "method1":
        method1();
        break;
    case "method2":
        method2();
        break;
    default:
        System.out.println(methodName + " is not a valid method!");
}

I was considering the option to invoke the method by its given string, as provided in this question:

How do I invoke a Java method when given the method name as a string?

But then I read from one of the answers, that it's not safe. What do you guys think?

Community
  • 1
  • 1
Pascal Weber
  • 557
  • 3
  • 11
  • 19

2 Answers2

1

If you need to go from a string to a method call, reflection may be your best option. There are no great safety issues involved, especially if you constrain the set of methods that are allowed to be called. Using a Map<String, Method> is one way to achieve it, with the benefit of improved performance since the main bottleneck is not reflective method invocation, but method lookup.

Without reflection you could achieve this with a Map<String, Callable>, where you implement Callable with an anonymous class instance for each method call. Quite a bit more boilerplate code, but "type safe".

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • great! how should the MethodCall look like? `Main.class.getMethod(command).invoke(null)`? – Pascal Weber Nov 15 '12 at 14:12
  • If `command` is a static method, then that's it. Otherwise, instead of `null` use the instance on which you want to call the method. Don't trip on exception handling, though: `try { ...reflection... } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }`. – Marko Topolnik Nov 15 '12 at 14:13
  • I am having trouble with that though.. but it points to the right direction. Marked it as best answer! – Pascal Weber Nov 15 '12 at 14:36
0

You can achieve the same functionality as reflection by using the Command design pattern. It wraps action into objects, so they can be looked up and invoked using a common interface.

Read more here: http://en.wikipedia.org/wiki/Command_pattern

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48