Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JavaScript in Java? [closed]

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?

like image 553
Dungeon Hunter Avatar asked Sep 20 '11 15:09

Dungeon Hunter


People also ask

Can I use JavaScript with Java?

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.

How do I execute JavaScript?

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.

What is one of the reasons Java is different to JavaScript?

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.


2 Answers

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.

like image 123
kdabir Avatar answered Sep 20 '22 01:09

kdabir


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.   } } 
like image 32
maerics Avatar answered Sep 18 '22 01:09

maerics