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

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

问题描述

假设我有这段代码,它使用一些输入(例如 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天全站免登陆