Java - 如何使用在文本文件中声明的变量

时间:2015-12-07 15:03:32

标签: java arraylist

我想使用在文件中声明的变量,它是一个Function变量(接口)。 对于函数的每个声明(每行一个),我想将它添加到函数表中。可能吗 ?是否有函数来检索代码中声明的变量?

感谢。

TestFunction.java

    ArrayList<Function> functions = new ArrayList<Function>();=

    Path file = Paths.get("./FunctionsDeclarations");
    try (InputStream in = Files.newInputStream(file);
        BufferedReader reader =
          new BufferedReader(new InputStreamReader(in))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
    //Ex: line = "Function f = times(X, compose(SIN, times(constant(2.), X)));"
    //I want to use the Function variable f after the reading file : functions.add(f);
            new ScriptEngineManager().getEngineByName("js").eval(line);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

FunctionsDeclarations

Function f = times(X, compose(SIN, times(constant(2.), X)));
Function f2 = times(X, compose(SIN, times(constant(8.), X)));
Function f3 = X;

1 个答案:

答案 0 :(得分:1)

您可以使用ScriptEngine实例来评估函数并稍后调用:

    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName("js");

    engine.eval("f = function() { return 1; }");

    Invocable invocable = (Invocable) engine;
    System.out.println(invocable.invokeFunction("f"));
在此示例中打印

1.0。

如果您需要评估Java表达式,请查看JEXL:https://commons.apache.org/proper/commons-jexl/

相关问题