运行String中包含的一段代码

运行String中包含的一段代码

问题描述:

我在String中有一段Java代码。

I have a piece of Java code in a String.

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

是否可以将此Java字符串转换为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.