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

0 Responses to “Adding a JavaScript host object with Rhino”



  1. Leave a Comment

Leave a Reply




About

I’m David Illsley, I work in Web Services development at IBM Hursley, which involves work on the Apache WS Project, where I am a committer and PMC member. When not working with technology, I spend a lot of time on the backstage aspects of theatre, and a sadly decreasing amount of time reading.

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 IBM or IBM management.

Twitter Updates

  • @katshann methinks someone's playing referrer games... (not me)... I'm barely in the top 30 search terms for my blog in the last 30 days 2 hours ago
  • @goodgravy Good luck! Sounds hopeful... 14 hours ago
  • Struggling to 'Open Link in New Tab' in recent Firefox nightlies. Muscle memory is just too strong 3 days ago
  • Dice games... what's the worst that can happen... #fb 5 days ago
  • Apparently one of my colleagues is 'prepared for DELETION'. That's a little more Logan's Run than I think he's expecting. 6 days ago