Call method by its name stored in string without reflection API?

cglib, java, reflection

Solution

This is what reflection is for. Before ruling it out, I'd suggest giving it a try and seeing whether, on any JVM from the last several years, you actually see any performance issue related to it. I suspect you won't.

Your only other real option (actually, there's `cglib`; see this other answer for more, and why you may not want to use it) is a method that you let people call, pass in the name of the method to call, and then dispatch to that method (e.g., with a big `switch`, or a dispatch table, or similar). E.g.:

public Object callMethod(String methodName, Object[] args) {
    switch (methodName) { // Using strings in `switch` requires a recent version of Java
        case "foo":
            return this.foo(args[0]);
        case "bar":
            this.bar(args[0], args[1]);
            return null;
        // ...and so on...
        default:
            throw new AppropriateException();
    }
}

Problem

I know, using Reflection API, we can call methods by their name stored in a string. But, Reflection API cannot be used in a high performance application. In my application, methods will be invoked at very high rate. So, I cannot use Reflection API. So, what are the alternatives for Reflection API? I did research and found out cglib and other code generation libraries can be used. But, I did not find any example to invoke method by its name stored in a string. An example would also be great with the reflection alternative. Update: Actually I am implementing some Master-Slave communication API. In which slaves will call master methods remotely. And, method invocations will be at very high rate (Approx 50 method invocation per second). As, master is continuously polling slaves for any response. So, should I give reflection a go at this high invocation rate?

Original source

Related problems