运行字符串中包含的代码

我在String中有一段Java代码。


String javaCode = "if(polishScreenHeight >= 200 && " +

    "polishScreenHeight <= 235 && polishScreenWidth >= 220) { }";

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


蛊毒传说
浏览 438回答 3
3回答

九州编程

正如已经建议的那样,您可以使用Compiler API即时编译,保存和运行代码。另一个简洁的选择是使用beanshell。Beanshell不再被积极开发,但是我可以保证它的可靠性,我已经在多个生产项目中成功使用了它。

GCT1015

您可以使用此代码来运行使用此代码的方法 new Statement(Object target, String methodName, Object[] arguments).execute();import java.beans.Statement;public class HelloWorld {&nbsp; public void method_name(String name) {&nbsp; &nbsp; &nbsp; System.out.println(name);&nbsp; }&nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; HelloWorld h = new HelloWorld();&nbsp; &nbsp; &nbsp; new Statement(h, "method_name", new Object[]{"Hello world"}).execute();&nbsp; }&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java