I'm embedded Rhino into our application (for end user scripting), and
I'd like to expose some dates into Javascript so that it feels as
native as possible (i.e. they are JS date objects, not
java.util.Date).
Rhino doesn't seem convert the Java date type into the native JS
type. So only the java date methods are available to the user.
I'm happy to manually instantiate a "native" Javascript object, but
how do I do this from Java? The NativeDate type is package protected,
and I can't see any obvious way to do this.
Thanks in advance,
Matt
From Java to JS, with date being a java.util.Date and cx being a
org.mozilla.javascript.Context:
Object[] args = { new Long(date.getTime()) };
cx.newObject(scope, "Date", args);
And from JS to Java, with s as org.mozilla.javascript.Scriptable:
if ("Date".equals(s.getClassName())
date = new Date((long) ScriptRuntime.toNumber(s));
I agree there should be an easy way to do this.
Hannes
> Thanks in advance,
> Matt
Thanks for this. But I was really aiming for a way to make any
java.util.Date that my APIs exposed be automatically turned into a JS
Date. After much investigation I ended up defining my own
"WrapFactory", and defined my own wrap method as follows (and it works
nicely).
public Object wrap(Context cx, Scriptable scope, Object obj, Class<?>
staticType) {
if (obj instanceof Date) {
// Construct a JS date object
return cx.newObject(scope, "Date", new Object[] {((Date)
obj).getTime()});
}
return super.wrap(cx, scope, obj, staticType);
}
I also had to set "setJavaPrimitiveWrap(false);" on the wrap factory,
so that "java.lang.Boolean" evalute correctly as true/false in JS. If
I didn't do this, then the following would print "FALSE is true?!?".
if (java.lang.Boolean.FALSE) {
// this would run
java.lang.System.out.println("FALSE is true?!?");
}
Cheers,
Matt