运行时代码生成和编译 [英] Runtime code generation and compilation

查看:153
本文介绍了运行时代码生成和编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个代码使用一些输入(例如URL路径)来确定通过反射运行哪个方法:

Say I have this code that uses some input (e.g. a URL path) to determine which method to run, via reflection:

// init
map.put("/users/*", "viewUser");
map.put("/users", "userIndex");

// later
String methodName = map.get(path);
Method m = Handler.class.getMethod(methodName, ...);
m.invoke(handler, ...);

这使用反射,因此可以提高性能。可以这样做:

This uses reflection so the performance can be improved. It could be done like this:

// init
map.put("/users/*", new Runnable() { public void run() { handler.viewUser(); } });
map.put("/users", new Runnable() { public void run() { handler.userIndex(); } });

// later
Runnable action = map.get(path);
action.run();

但手动创建所有 Runnable 之类的这有其自身的问题。
我想知道,我可以在运行时生成它们吗?所以我在第一个例子中有一个输入映射,并会动态创建第二个例子的映射。
当然,生成它只是建立一个字符串的问题,但是编译和加载它呢?

But manually creating all those Runnables like that has its own issues. I'm wondering, can I generate them at runtime? So I'd have an input map as in the first example, and would dynamically create the map of the second example. Sure, generating it is just a matter of building a string, but what about compiling and loading it?

注意:我知道性能提升很少,这是过早优化的完美例子。因此,这是一个学术问题,我对运行时生成和代码编译感兴趣。

Note: I know the performance increase is so little it's a perfect example of premature optimization. This is therefore an academic question, I'm interested in runtime generation and compilation of code.

推荐答案

生成代码的唯一方法动态是生成源代码并编译它或生成字节代码并在运行时加载它。前者有模板解决方案,后者有字节码操作库。没有真实的案例和一些分析我不认为你真的可以说哪个更好。从维护的角度来看,我认为反射是可行的最佳选择。

The only ways to generate code dynamically are to either generate source code and compile it or to generate byte code and load it at runtime. There are templating solutiions out there for the former, and bytecode manipulation libraries for the latter. Without a real case and some profiling I don't think you can really say which will be better. From a maintenance point of view I think reflection is the best option when available.

这篇关于运行时代码生成和编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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