1

我对 Rhino 很陌生,并试图将 javascript 对象转换为 java 对象但无法这样做。它似乎没有正确评估。

我拥有的javascript是,

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

我有以下 java 类,我想对其进行评估,

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

我的解析器的骨架是,

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

谢谢

4

1 回答 1

2

好的,想通了!

首先,我需要将 javascript 中的类定义为。起初它抱怨找不到没有命名空间“com”的类。不得不补充...

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

然后在解析器中我添加了以下内容,

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;
}
于 2013-09-02T04:07:53.347 回答