我将 Java 代码作为字符串存储在数据库中。例如:
String x = "System.out.println(\"X\")";
我需要将其转换为java.lang.Runnable
才能在任务执行器服务中运行它。我怎样才能创建它?
private Runnable StringToRunnable(String task){
Runnable runnable = null;
return runnable;
}
最佳答案
Janino是按需编译器的流行选择。许多开源项目都在使用它。
用法很简单。代码
import org.codehaus.janino.ScriptEvaluator;
public class App {
public static void main(String[] args) throws Exception {
String x = "System.out.println(\"X\");"; //<-- dont forget the ; in the string here
ScriptEvaluator se = new ScriptEvaluator();
se.cook(x);
se.evaluate(new Object[0]);
}
}
打印x
。
正如其他人已经指出的那样,从数据库加载代码并执行它可能有点冒险。
关于java - 如何在 Java 中将字符串转换为可运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275210/