使用Java反射创建eval()方法 [英] Using Java reflection to create eval() method

查看:48
本文介绍了使用Java反射创建eval()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于反思的问题我正在尝试某种eval()方法.因此,我可以举个例子:

I have a question about reflection I am trying to have some kind of eval() method. So i can call for example:

eval("test('woohoo')");

现在,我了解到Java中没有eval方法,但存在反射.我编写了以下代码:

Now I understand the there is no eval method in java but there is reflection. I made the following code:

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

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

This works perfectly (of course there is a try, catch block around this code). It runs the test method. However I want to call multiple methods who all have different parameters.

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

I don't know what parameters these are (so not only String.class). But how is this possible? how can I get the parameter types of a method ? I know of the following method:

Class[] parameterTypes = method.getParameterTypes();

但这将返回我刚刚选择的方法的parameterTypes!带有以下语句:

But that will return the parameterTypes of the method I just selected! with the following statement:

Method method = cl.getMethod(s, String.class);

任何帮助将不胜感激!

推荐答案

您将需要调用 Class.getMethods() 并遍历它们以寻找正确的功能.

You will need to call Class.getMethods() and iterate through them looking for the correct function.

For (Method method : clazz.getMethods()) {
  if (method.getName().equals("...")) {
    ...
  }
}

这样做的原因是,可能有多个具有相同名称和不同参数类型的方法(即,方法名称已重载).

The reason for this is that there can be multiple methods with the same name and different parameter types (ie the method name is overloaded).

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

getMethods() returns all the public methods in the class, including those from superclasses. An alternative is Class.getDeclaredMethods(), which returns all methods in that class only.

这篇关于使用Java反射创建eval()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆