1

Im quite new to Rhino and trying to convert a javascript object to a java object but unable to do so. It doesnt seem to evaluate properly.

The javascript that I have is,

var myObject = new Object();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);

And I have the following java class that I want to evaluate this to,

public class Person extends ScriptableObject {
 private int id;
 private String string1;
 private String string2;
 public Person() {}
 public void jsConstructor() {
 this.string1 = "";
 this.string2 = "";
 this.id = 0;
 }
 public int getID()
 {
 return this.id;
 }
 public void jsSet_id(int value)
 {
 this.id = value;
 }
 public int jsGet_id()
 {
 return this.id;
 }
 public String jsGet_string1()
 {
 return this.string1;
 }
 public void jsSet_string1(String value)
 {
 this.string1 = value;
 }
 public String jsGet_string2() {
 return this.string2;
 }
 public void jsSet_string2(String value)
 {
 this.string2 = value;
 }
 @Override
 public String toString() {
 return id + " " + string1 + " " + string2;
 }
 @Override
 public String getClassName() {
 return "Person";
 }

And the skeleton of my parser is,

public class MyParser {
 public String PrintObj(ScriptableObject obj) {
 // Need to convert to Person object here
 // Obviously casting doesnt work here
 return null;
 }
}

Thanks

asked Sep 2, 2013 at 3:48

1 Answer 1

2

OK figured it out !

First of all i needed to define the class in javascript as. It was complaining at first it couldn't find the class without the namespace "com". Had to add that...

defineClass("com.Person")
var myObject = new Person();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);

And then in the parser I added the following,

public String PrintObj(ScriptableObject obj) {
 try {
 Person pObj = (Person)Context.jsToJava(obj, Person.class);
 System.out.println("Printing person: " + pObj);
 }
 catch (Exception e) {
 e.printStackTrace();
 }
 return null;
}
answered Sep 2, 2013 at 4:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.