I wanted to build a small product in which I wanted to give a kind of feature in which user can write a script language kind of JavaScript.
And also from JavaScript able to build objects and calling methods on them.
Is there any framework for this?
This question is related to
java
javascript
apache
object
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
I just wanted to answer something new for this question - J2V8
.
Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:
Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""
You can use ScriptEngine, example:
public class Main {
public static void main(String[] args) {
StringBuffer javascript = null;
ScriptEngine runtime = null;
try {
runtime = new ScriptEngineManager().getEngineByName("javascript");
javascript = new StringBuffer();
javascript.append("1 + 1");
double result = (Double) runtime.eval(javascript.toString());
System.out.println("Result: " + result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Source: Stackoverflow.com