Java-如何使用文本文件中声明的变量
我想使用文件中声明的变量,因为它是函数变量(接口)。 对于函数的每个声明(每行一个),我想将其添加到函数表中。可能吗?是否有一个函数来检索代码中声明的变量 谢谢 TestFunction.javaJava-如何使用文本文件中声明的变量,java,arraylist,Java,Arraylist,我想使用文件中声明的变量,因为它是函数变量(接口)。 对于函数的每个声明(每行一个),我想将其添加到函数表中。可能吗?是否有一个函数来检索代码中声明的变量 谢谢 TestFunction.java ArrayList<Function> functions = new ArrayList<Function>();= Path file = Paths.get("./FunctionsDeclarations"); try (InputStream
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);
}
您可以使用
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:请提出明确的问题,并为给定的输入提供预期的输出。@user3185672我仍然不清楚。查看您的问题标题和问题,令人困惑
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"));