-1

How can I call a method using String in Java. For example,

    String a = "call";
    int b = a();

    private static int call() {
         return 1;
    }

I know that it's got something to do with reflection, but I am not sure how to get it to work.

newguuy
  • 1
  • 2

2 Answers2

0

You can do this with reflection. First get a reference to the Class, use that to obtain the Method by-name. Then you can invoke that method. For example,

public class Test {    
    public static int call() {
        return 42;
    }

    public static void main(String[] args) throws Exception {
        Method m = Test.class.getMethod("call", new Class[0]);
        Object o = m.invoke(null, new Object[0]);
        System.out.println(o);
    }
}

Outputs the meaning of life, the universe and everything.

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
0

Reflection. Or Method Handles.

Reflection:

 import java.lang.Reflect;

 public class SomeClass {
     public void someMethod() {
         String a = "call";

         try {
             Method m = SomeClass.class.getDeclaredMethod(a);
             m.setAccessible(true);
             m.invoke(null);
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
    }
}

Without Reflection, using MethodHandles:

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class Example {
    public static void main(String[] args) {
        String a = "call";
        try {
            MethodHandle h = MethodHandles.lookup()
                .findStatic(Example.class, a, MethodType.methodType(Integer.TYPE));
            int result = (int) h.invokeExact();
            System.out.println(result);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unused")
    private static int call() {
        return 42;
    }
}

MethodHandles are said to be faster, but they have some additional limitations, like you can only use them to call code that you can call in the current context.

This limitation works for us in this case, because call is private, so we can call it. But if we try to do that from a different class, we will get an exception. (We can pass the result of lookup() or findStatic(), and others can call it for us.)

Also, the MethodHandles example works if there is a SecurityManager.

Johannes Kuhn
  • 12,878
  • 3
  • 41
  • 66