Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a java application with a method (A) which should use a javascript function (B), evaluated with rhino, to change some objects before returning them with A. The point is, that the parameter passed from within A to B are complex (List) and also the returned type from B should be from the same type. Currently I have no idea how to use my own classes in the javascript function. Who do I import them in JavaScript?

I use rhino how to call js function from java to load and run my javascript function.

Thanks in advance!

share|improve this question
    
import what into javascript? your java class? – MaVRoSCy Jul 14 '12 at 10:40
    
@MaVRoSCy: Yep I want to use my own Classes in JavaScript. Serialization to JSON was one idea I had... – jstr Jul 14 '12 at 11:04
up vote 0 down vote accepted

See example. It uses jsr223, but you will get the idea. I am passing list with one instance of MyClass to rhino, it modifies it (via java method call) and finally adds yet another element to list.

package lv.test;

import java.util.ArrayList;
import java.util.List;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class MyClass {
    private int field;

    public int getField() {
        return field;
    }

    public void setField(final int field) {
        this.field = field;
    }

    public String toString() {
        return String.format("{%d}", field);
    }

    public static void main(String[] args) throws ScriptException {
        final ScriptEngineManager manager = new ScriptEngineManager();
        final ScriptEngine e = manager.getEngineByName("js");

        final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);

        final List<MyClass> somelist = new ArrayList<MyClass>();
        somelist.add(new MyClass());

        b.put("somelist", somelist);

        final StringBuilder script = new StringBuilder()
            .append("function abc(x,y) { return x+y+new java.lang.Integer(2).intValue(); }")
            .append("somelist.get(0).setField(abc(2,3));")
            .append("somelist.add(new Packages.lv.test.MyClass()); somelist.get(1).setField(888);");

        e.eval(script.toString());

        System.out.println(somelist); // [{7}, {888}]
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.