运行包含在一个string中的一段代码

我在String中有一段Java代码。

String javaCode = "if(polishScreenHeight >= 200 && " + "polishScreenHeight <= 235 && polishScreenWidth >= 220) { }"; 

是否有可能将此Javastring转换为Java语句并运行它? 可能使用Javareflection?

正如已经build议的那样,您可以使用Compiler API来编译,保存和运行代码。

另一个很好的select是使用beanshell 。 Beanshell不再积极开发,但我可以保证它的可靠性,我已经成功地在多个生产项目中使用它。

使用BeanShell。 有一个关于如何从Java使用它的页面。

Beanshell(正如Boris所build议的)是“执行”java源代码的一种方式。 但是看起来像是要“执行”可以与编译类进行交互的片段。 你的例子包含可变名称。

reflection将毫无帮助,因为reflection目标类(“classfiles”)。

可以尝试定义一个完整的类(“有效的java源文件”),编译并加载它(url classloader)。 那么你应该可以使用这个“生成的类”的方法。 但是一旦一个类被加载,你不能摆脱它(卸载),所以这只会工作一次(AFAIK)。

据我所知,没有简单的方法来做到这一点。

但是,在Java 6以后,您可以使用javax.tools.Compiler编译完整类的源代码。 编译后的类可以被加载并执行。 但我不认为这会达到你想要的。

另一种方法是将代码作为Groovy代码执行,请参阅此示例。

您可以使用此代码来运行使用此代码的方法

 new Statement(Object target, String methodName, Object[] arguments).execute(); import java.beans.Statement; public class HelloWorld { public void method_name(String name) { System.out.println(name); } public static void main(String[] args) throws Exception { HelloWorld h = new HelloWorld(); new Statement(h, "method_name", new Object[]{"Hello world"}).execute(); } } 

尝试JavaCompiler API。

有人比我更好地回答了这个问题,但是: 将string转换为代码

实际使用这样的东西之前要小心…