使用Javareflection创建eval()方法
我有一个关于reflection的问题我试图使用某种eval()方法。 所以我可以举个例子:
eval("test('woohoo')");
现在我明白java中没有eval方法,但有reflection。 我做了以下代码:
String s = "test"; Class cl = Class.forName("Main"); Method method = cl.getMethod(s, String.class); method.invoke(null, "woohoo");
这完美地工作(当然有一个尝试,围绕这个代码的catch块)。 它运行测试方法。 但是我想调用多个方法,这些方法都有不同的参数。
我不知道这些参数是什么(所以不仅仅是String.class)。 但这怎么可能呢? 如何获取方法的参数类型? 我知道以下方法:
Class[] parameterTypes = method.getParameterTypes();
但是这将返回我刚刚选择的方法的parameterTypes! 以下声明:
Method method = cl.getMethod(s, String.class);
任何帮助,将不胜感激 !
您将需要调用Class.getMethods()
并遍历它们以查找正确的函数。
For (Method method : clazz.getMethods()) { if (method.getName().equals("...")) { ... } }
原因是可以有多个具有相同名称和不同参数类型的方法(即方法名称被重载)。
getMethods()
返回类中的所有公共方法,包括来自超类的公共方法。 另一种方法是Class.getDeclaredMethods()
,它仅返回该类中的所有方法。
您可以使用以下方法遍历类的所有方法:
cls.getMethods(); // gets all public methods (from the whole class hierarchy)
要么
cls.getDeclaredMethods(); // get all methods declared by this class
。
for (Method method : cls.getMethods()) { // make your checks and calls here }
您可以使用getMethods()
返回类的所有方法的数组。 在循环内部,您可以检查每个方法的参数。
for(Method m : cl.getMethods()) { Class>[] params = m.getParameterTypes(); ... }
否则你可以使用getDelcaredMethods()
,这将允许你“看到”私有方法(但不是inheritance的方法)。 请注意,如果要调用私有方法,则必须首先对其应用setAccessible(boolean flag) :
for(Method m : cl.getDelcaredMethods()) { m.setAccessible(true); Class>[] params = m.getParameterTypes(); ... }
对于在这里回答我问题的所有人来说,最后的解决方案:
import java.lang.reflect.Method; public class Main { public static void main(String[] args){ String func = "test"; Object arguments[] = {"this is ", "really cool"}; try{ Class cl = Class.forName("Main"); for (Method method : cl.getMethods()){ if(method.getName().equals(func)){ method.invoke(null, arguments); } } } catch (Exception ioe){ System.out.println(ioe); } } public static void test(String s, String b){ System.out.println(s+b); } }
- 代理实例如何将自身传递给InvocationHandler?
- kCFStreamPropertySocketSecurityLevel到kCFStreamSocketSecurityLevelNegotiatedSSL导致连接到Java的OSStatus errSSLXCertChainInvalid(-9807)
- 域名未指向已安装的Java WebApplication在并行plesk中,删除端口号
- 使用ibatis检索新插入的ID时的并发问题
- 在java中生成随机数列表
- 如何在eclipselink中禁用缓存
- 澄清Java / SQLite批处理和自动提交
- Double.intValue()如何工作?
- java中的二维字符串数组