运行包含在字符串中的一段代码

问题描述:

我在字符串中有一段 Java 代码.

I have a piece of Java code in a String.

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

是否可以将此 Java String 转换为 Java 语句并运行它?可能使用 Java 反射?

Is it possible to convert this Java String to a Java statement and run it? Possibly using Java reflection?

正如已经建议的那样,您可以使用 编译器 API.

As has already been suggested you can compile, save and run code on the fly using the Compiler API.

另一种巧妙的替代方法是使用 beanshell.Beanshell 不再积极开发,但我可以保证它的可靠性,我已经在多个生产项目中成功使用了它.

Another neat alternative would be to use beanshell. Beanshell is no longer actively developed, but I can vouch for it's reliability, I've used it successfully in multiple production projects.