[英]Java - How to use a variable declared in a text file
I would like to use a variable declared in a fileknowing that it is a Function variable (interface). 我想使用一个在文件中声明的变量,因为它是一个功能变量(接口)。 For each declaration of a function (one per line), I would like to add it to a function table.
对于函数的每个声明(每行一个),我想将其添加到函数表中。 Is it possible ?
可能吗 ? Is there a function to retrieve the variables declared in the code ?
是否有一个函数可以检索代码中声明的变量?
Thanks. 谢谢。
TestFunction.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 FunctionsDeclarations
Function f = times(X, compose(SIN, times(constant(2.), X)));
Function f2 = times(X, compose(SIN, times(constant(8.), X)));
Function f3 = X;
You can eval functions and invoke later, using a ScriptEngine
instance: 您可以使用
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 is printed in this example. 在此示例中打印了1.0。
If you need to evaluate Java expressions, take a look at JEXL: https://commons.apache.org/proper/commons-jexl/ 如果需要评估Java表达式,请查看JEXL: https ://commons.apache.org/proper/commons-jexl/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.