通过存储在字符串中的名称调用方法而无需反射 API? [英] Call method by its name stored in string without reflection API?

查看:63
本文介绍了通过存储在字符串中的名称调用方法而无需反射 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,使用反射 API,我们可以通过存储在字符串中的名称来调用方法.

I know, using Reflection API, we can call methods by their name stored in a string.

但是,反射 API 不能用于高性能应用程序.在我的应用程序中,方法将以非常高的速度被调用.所以,我不能使用反射 API.

But, Reflection API cannot be used in a high performance application. In my application, methods will be invoked at very high rate. So, I cannot use Reflection API.

那么,反射 API 有哪些替代方案?

So, what are the alternatives for Reflection API?

我做了研究,发现可以使用 cglib 和其他代码生成库.

I did research and found out cglib and other code generation libraries can be used.

但是,我没有找到任何通过存储在字符串中的名称来调用方法的示例.

But, I did not find any example to invoke method by its name stored in a string.

使用反射替代方案的示例也很棒.

An example would also be great with the reflection alternative.

更新:实际上我正在实现一些主从通信 API.其中,slave 将远程调用 master 方法.而且,方法调用的速率非常高(每秒大约 50 次方法调用).因为,主机不断轮询从机以获取任何响应.那么,我应该在如此高的调用率下进行反思吗?

Update: Actually I am implementing some Master-Slave communication API. In which slaves will call master methods remotely. And, method invocations will be at very high rate (Approx 50 method invocation per second). As, master is continuously polling slaves for any response. So, should I give reflection a go at this high invocation rate?

推荐答案

这就是反射的作用.在排除它之前,我建议您尝试一下,看看在过去几年的任何 JVM 上,您是否真的看到了与它相关的任何性能问题.我怀疑你不会.

This is what reflection is for. Before ruling it out, I'd suggest giving it a try and seeing whether, on any JVM from the last several years, you actually see any performance issue related to it. I suspect you won't.

你唯一的其他选择 (实际上,还有 cglib; 查看其他答案了解更多信息,以及您可能不想使用它的原因) 是一种让人们调用的方法,传入要调用的方法的名称,然后分派给该方法(例如,使用一个大的switch,或者一个分派表,或者相似的).例如:

Your only other real option (actually, there's cglib; see this other answer for more, and why you may not want to use it) 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();
    }
}

这篇关于通过存储在字符串中的名称调用方法而无需反射 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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