动态代码执行 [英] Dynamic code execution

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

问题描述

与动态SQL类似,其中String在运行时作为SQL执行,我们可以动态运行Java代码吗?就像我返回一个字符串,这是一个Java代码,然后我在运行时执行。这可能吗?

解决方案

对于真正的Java代码,可以使用 JavaCompiler 界面。但是,它使用起来非常不方便,因为它只是一个真正的Java编译器的接口,它希望编译文件中的整个类定义。



执行代码的最简单方法在运行时将使用 Rhino JavaScript引擎



这两个选项都只在Java 6中,但我相信之前存在脚本接口,所以如果你下载并将它添加到类路径中,你可以在早期的JRE中使用Rhino。 / p>

Similar to dynamic SQL, wherein a String is executed as an SQL at runtime, can we have Java code run dynamically? Like I return a String which is a Java code and then I execute at runtime. Is this possible?

解决方案

For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.

The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.

Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.

这篇关于动态代码执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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