Some days ago I was experimenting on an easy way to evaluate a calculation saved within a String variable of my program.
After some searches and a very useful hint I finally found the Java "ScriptEngineManager" introduced in Java 6 (JavaDoc). This engine is a very useful extension to the Java programming language as it allows to natively import the functionality of (in this case) JavaScript (documentation).
With this knowledge I wrote this simple test-program to show the possibilities of this technology:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptTest {
public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
Number ret = (Number) jsEngine.eval("10 + 5 * (2 +3 *6)");
System.out.println(ret.doubleValue());
Boolean ret1 = (Boolean) jsEngine.eval("100 >= (6*5)");
System.out.println(ret1.booleanValue());
jsEngine.put("Hallo", "Servus");
String ret2 = (String) jsEngine.eval("Hallo");
System.out.println(ret2);
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
Subscribe to:
Post Comments (Atom)
Golang setup PATH
Quite recently we startet in the company to use and write some Go programs. I love Go. It's easy to learn, read and modify. One of the m...
-
Just recently I had to replace my old Wifi-Setup with a new system. After some investigation on the topic (and a good offer from amazon ware...
-
Quite recently we startet in the company to use and write some Go programs. I love Go. It's easy to learn, read and modify. One of the m...
-
As the client for Java is missing at the jasig homepage I'll provide my solution here. Of course it has the "Domain" addition...
No comments:
Post a Comment