Adding a JavaScript host object with Rhino

I’ve been thinking a fair bit about server side JavaScript recently, but haven’t really dug in. One of the things I’ve been wondering is how easy it is to define a host object with Rhino. Turns out it’s trivial:

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class Test {
public static class TestHost extends ScriptableObject {
  private String val = "";
  public String getClassName() {
    return "TestHost";
  }
  public String jsGet_val() {
    return val;
  }
  public void jsSet_val(String s) {
    val = s;
    System.out.println("from java: " + s);
  }
}

public static void main(String args[]) throws Exception {
  Context c = Context.enter();
  ScriptableObject so = c.initStandardObjects();
  ScriptableObject.defineClass(so, TestHost.class);
  System.out.println(c.evaluateString(so,
      "var t = new TestHost(); t.val='ee';'from script: '+t.val", "",
      1, null));
  }
}

Results in:

from java: ee
from script: ee
Advertisement

1 Response to “Adding a JavaScript host object with Rhino”


  1. 1 Marko Zavodjenje December 13, 2010 at 10:06 am

    Thank you for this useful information.


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




About

I’m David Illsley, I’m a Software Engineer, currently working for Morgan Stanley in London. In the past I worked for IBM developing products in the WebSphere family, and before that I studied at Edinburgh University. I'm also a PMC member @TheASF, and outside the realms of technology, enjoy skulking around the dark corners of theatre...

Archives

c

Disclaimer

The postings on this site solely reflect the personal views of the author and do not necessarily represent the views, positions, strategies or opinions of my employer.

Twitter Updates

  • *aaah* Another long weekend. I could get used to this. #fb 3 days ago
  • @ajdaniel what is now crap? Have you played with the new built in dev tools? 6 days ago
  • Frustrating not to make it to either fosdem or monkigras this week... It's like 3 buses at once or something 6 days ago
  • Wow, Danish crematoria are are pretty, uh, matter of fact… #borgen 1 week ago
  • @sd_nicholas it's a hedge against changes as it predates the final spec. Unprefixed version I think is due soon. 2 weeks ago

Follow

Get every new post delivered to your Inbox.