![](/img/trans.png)
[英]How to use a variable value declared in servlet into a new Java class?
[英]Java - How to use a variable declared in a text file
我想使用一個在文件中聲明的變量,因為它是一個功能變量(接口)。 對於函數的每個聲明(每行一個),我想將其添加到函數表中。 可能嗎 ? 是否有一個函數可以檢索代碼中聲明的變量?
謝謝。
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;
您可以使用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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.