在Java中使用字符串调用方法

在Java中使用字符串调用方法,java,Java,如何在Java中使用字符串调用方法。比如说, String a = "call"; int b = a(); private static int call() { return 1; } public class Test { public static int call() { return 42; } public static void main(String[] args) thro

如何在Java中使用字符串调用方法。比如说,

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

    private static int call() {
         return 1;
    }
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);
    }
}

我知道这与反射有关,但我不知道如何让它工作。

你可以用反射来做这件事。首先获取对
类的引用
,使用该引用按名称获取
方法
。然后可以调用该方法。比如说,

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

    private static int call() {
         return 1;
    }
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);
    }
}

输出生命、宇宙和万物的意义。

反射。或方法句柄

反思:

 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);
         }
    }
}
在没有反射的情况下,使用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据说速度更快,但它们还有一些额外的限制,比如只能使用它们来调用可以在当前上下文中调用的代码

这种限制在这种情况下对我们有效,因为
call
是私有的,所以我们可以调用它。但是,如果我们尝试从另一个类执行此操作,我们将得到一个异常。(我们可以传递
lookup()
findStatic()
的结果,其他人可以为我们调用它。)


此外,MethodHandles示例在Java中存在一个无效语句的
SecurityManager

时也可以使用。你不认为让一个方法接收字符串并使用开关大小写调用一个特定的方法更容易吗?你必须使用反射。user7我知道它无效,这就是为什么我问是否有办法看到这一点。生活的意义是什么?(我要试试这个东西。也许我能解决弦论的问题)。@DevilsHnd和。