2015-12-07 50 views
1

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

谢谢。

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; 
+2

请让一个清晰的问题,并提供了一个给定的输入的预期输出。 – Manu

+0

@ user3185672但仍然不清楚。看到你的问题标题和问题,令人困惑 –

回答

1

可以EVAL函数,并随后调用,使用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/