Nashorn: Javascript to Java call question

Jim Laskey (Oracle) james.laskey at
Wed Jun 5 12:51:19 PDT 2013

The repo you provided has empty JSON-java and JSON-js directories, so I'll give you an alternative example.  The main thing to note is that, because of a JS object's dynamic nature, it can not mirror a Java object.  A better analogy would be to think of a JS object as a Map object, where properties are keys and you access values with keys.

Run the enclosed example as follows;

	java Example

The class of myObject is a JSObject.  You can access properties of a JSObject with getMember/setMember (or getSlot/setSlot for integer keys.)

=== ===

import javax.script.*;
import jdk.nashorn.api.scripting.JSObject;

public class Example {
	public static void main(String[] args) throws Exception {
		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName("nashorn");
		JSObject myObject = (JSObject)engine.get("myObject");
       		myObject.setMember("d", "A new string");


=== Example1.js ===

var myObject = {
   a: "A string",
   b: 100,
   c: true

=== Example2.js ===


==== Output ===

A string
A new string


-- Jim

On 2013-06-05, at 3:50 PM, Mani Sarkar <sadhak001 at> wrote:

> Hi,
> I have another query regarding the example (see
> created sometime back  during the Nashorn hackday. When I bring a JS object
> created in Nashorn into Java I'm not able to access the object directly,
> how do I access it like a normal java object.
> If its a raw / primitive type then the contents are accessible (you can see
> the value) while for JS object, when I say
> *System.out.println(JSObjectFromNashorn);*
> I get the below output
> *[object object]*
> The full implementation of what I'm talking about can be found at the above
> link.
> Regards,
> mani
> -- 
> *Twitter:* @theNeomatrix369          *Blog:*
> *JUG activity:* LJC Advocate (@adoptopenjdk & @adoptajsr programs)
> *Meet-a-Project:*
> *Bitbucket:*  * **Github:* https://github
> .com/neomatrix369
> *LinkedIn:*
> *Devoxx UK 2013* was a grand success:
> *Don't chase success, rather aim for "Excellence", and success will come
> chasing after you!*

More information about the nashorn-dev mailing list