我在String中有一段Java代码。String javaCode = "if(polishScreenHeight >= 200 && " + "polishScreenHeight <= 235 && polishScreenWidth >= 220) { }";是否可以将此Java String转换为Java语句并运行它?可能使用Java反射?
3 回答

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

GCT1015
TA贡献1827条经验 获得超4个赞
您可以使用此代码来运行使用此代码的方法 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();
}
}
添加回答
举报
0/150
提交
取消