我知道,使用 Reflection API,我们可以通过存储在字符串中的名称来调用方法。
但是,Reflection API 不能用于高性能应用程序。
在我的应用程序中,方法将以非常高的速率被调用。所以,我不能使用Reflection API。
那么,Reflection API 有哪些替代方案呢?
我做了研究,发现可以使用 cglib 和其他代码生成库。
但是,我没有找到任何通过存储在字符串中的名称来调用方法的示例。
一个关于反射替代方案的例子也很好。
Update:实际上我正在实现一些主从通信API。其中从站将远程调用主站方法。而且,方法调用的速率非常高(每秒大约 50 个方法调用)。因为,主设备不断轮询从设备是否有任何响应。那么,在如此高的调用率下,我应该尝试一下反思吗?
这就是反射for。在排除它之前,我建议您尝试一下,看看在过去几年的任何 JVM 上,您是否确实看到了与之相关的任何性能问题。我怀疑你不会。
Your only other real option (actually, there's cglib https://github.com/cglib/cglib; see this other answer for more, and why you may not want to use it https://stackoverflow.com/a/23580118/157247) is a method that you let people call, pass in the name of the method to call, and then dispatch to that method (e.g., with a big switch
, or a dispatch table, or similar). E.g.:
public Object callMethod(String methodName, Object[] args) {
switch (methodName) { // Using strings in `switch` requires a recent version of Java
case "foo":
return this.foo(args[0]);
case "bar":
this.bar(args[0], args[1]);
return null;
// ...and so on...
default:
throw new AppropriateException();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)