使用Java反射创建eval()方法

hel*_*ers 5 java reflection

我有一个关于反射的问题我试图使用某种eval()方法.所以我可以举个例子:

eval("test('woohoo')");
Run Code Online (Sandbox Code Playgroud)

现在我明白java中没有eval方法,但有反射.我做了以下代码:

String s = "test";
Class cl = Class.forName("Main");
Method method = cl.getMethod(s, String.class);
method.invoke(null, "woohoo");
Run Code Online (Sandbox Code Playgroud)

这非常有效(当然,这个代码周围有一个try,catch块).它运行测试方法.但是我想调用多个方法,这些方法都有不同的参数.

我不知道这些参数是什么(所以不仅是String.class).但这怎么可能呢?如何获取方法的参数类型?我知道以下方法:

Class[] parameterTypes = method.getParameterTypes();
Run Code Online (Sandbox Code Playgroud)

但是这将返回我刚刚选择的方法的parameterTypes!以下声明:

Method method = cl.getMethod(s, String.class);
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激 !

cle*_*tus 15

您将需要调用Class.getMethods()并遍历它们以查找正确的函数.

For (Method method : clazz.getMethods()) {
  if (method.getName().equals("...")) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

原因是可以有多个具有相同名称和不同参数类型的方法(即方法名称被重载).

getMethods()返回类中的所有公共方法,包括来自超类的方法.另一种方法是Class.getDeclaredMethods(),它返回在类的所有方法.


Boz*_*zho 5

您可以使用以下方法遍历类的所有方法:

cls.getMethods(); // gets all public methods (from the whole class hierarchy)
Run Code Online (Sandbox Code Playgroud)

要么

cls.getDeclaredMethods(); // get all methods declared by this class
Run Code Online (Sandbox Code Playgroud)

.

for (Method method : cls.getMethods()) {
    // make your checks and calls here
}
Run Code Online (Sandbox Code Playgroud)