如何在Java中将字符串转换为可运行代码

问题描述 投票:1回答:2

我将Java代码作为字符串存储在数据库中。例如:

String x = "System.out.println(\"X\")";

我需要将其转换为java.lang.Runnable才能在任务执行程序服务中运行。如何创建它?

private Runnable StringToRunnable(String task){
Runnable runnable = null;

return runnable;
}
java runnable
2个回答
0
投票

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

正如其他人已经指出的那样,从数据库中加载代码并执行它可能会有些冒险。


0
投票

我创建了此方法

    private void getMethod(String fromClass, String fromMethod) {
    Class<?> aClass;
    try {
        aClass = Class.forName(fromClass);
        Method method = aClass.getMethod(fromMethod);
        method.setAccessible(true);
        method.invoke(aClass.newInstance());
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
        e.printStackTrace();
    }
}

并由]称呼>

        Runnable task = () -> getMethod(fromClass, fromMethod);

并且我将className和方法名通过:]放入数据库中

this.getClass()。getCanonicalName()和字符串方法名称

© www.soinside.com 2019 - 2024. All rights reserved.