Rhino Evaluating a javascript object in Java

1.4k views Asked by At

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

1

There are 1 answers

0
nixgadget On BEST ANSWER

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;
}