سؤال

Im quite new to Rhino and my question is around how to achieve the following,

Say I have a javascript object that follows something like the following that I can consume within java.

var myObject = new Object();
myObject.string1 = "Hello";
myObject.string2 = "World";
myObject.int1 = 1;

But how do I consume this within java if its dynamic. For .e.g. if you decide to add few more members dynamically to this object within javascript. Is this doable ? My guess is the class defined within java will have to take all the possible members into account to do this ?

Hopefully I have explained what im trying to achieve correctly.

هل كانت مفيدة؟

المحلول

JavaScript objects, when you access them in Java, are all essentially the same class: ScriptableObject which implements the Scriptable interface (GitHub source). There are a few other classes for functions and other specialized objects.

The Scriptable interface includes methods like get, has, and put that correspond roughly to myObject.string1, myObject.hasOwnProperty("string1"), and myObject.string1 = "Hello" in JavaScript. The ScriptableObject class adds some other useful methods for defining properties, etc.

نصائح أخرى

Consider using a library like GSON for converting a javascript object to JAVA.

https://code.google.com/p/google-gson/

you can convert a javascript object to JSON using JSON.stringify

and then use GSON or another such library to generate a Java object.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top