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?
Java SE 6 makes it simple to use JavaScript within Java code. Other scripting engines can also be associated with Java, but it is handy to have one provided out-of-the-box with Mozilla Rhino.
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only. Java code needs to be compiled while JavaScript code are all in text. They require different plug-ins.
Rhino is what you are looking for.
Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.
Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.
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. } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With