I originally tried to ask this question to a Rhino Usenet group, but
didn't get any responses. See,
http://groups.google.com/group/netscape.public.mozilla.jseng/browse_frm/thread/f69fd9ee0c157fea
My question is how do I create a Java object from JavaScript that
allows you to getClass() to get the class, then newInstance() to
create a new object. Yes, that is not exactly the same as my subject
line, but that is because I think it is about the same thing.
Ultimately, I'm trying to create an HttpServlet in JavaScript. I can
already invoke Jetty from JavaScript by using Rhino's js.jar along
with the required jar files for Jetty. I can configure an HttpServlet
written in Java from JavaScript and it works properly. When I try to
extend the HttpServlet class using JavaScript, the object construction
seems to work, but I can't get Jetty to properly make an instance of
that object and respond to the HTTP queries.
To configure Jetty, you actually pass the class name you want to use
as a handler, not the object itself. Jetty will then create an
instance of that class at initialization time. I think this is
failing because there isn't an appropriate constructor for the class.
I've generated a simple example that does not use the Jetty jar files
to illustrate the issue. The example simply requires that you invoke
Rhino's JavaScript shell. Here is the code:
This works...
java_o1 = new java.lang.Thread;
java_c = java_o1.getClass();
java_o2 = java_c.newInstance();
This does not...
js_o = new Object;
js_o = { run: function() { print("got here"); } };
js_o.run();
java_o1 = new JavaAdapter(java.lang.Runnable, js_o);
// or java_o1 = new java.lang.Runnable(js_o);
java_o1.run();
java_c = java_o1.getClass();
java_o2 = java_c.newInstance();
I think this shows why the second example doesn't work:
js> for (i in java_c.constructors) { print("java_c.constructors[" + i +
"] = " + java_c.constructors[i]); }
java_c.constructors[0] = public
adapter1(org.mozilla.javascript.ContextFactory,org.mozilla.javascript.Scriptable)
java_c.constructors[1] = public
adapter1(org.mozilla.javascript.ContextFactory,org.mozilla.javascript.Scriptable,org.mozilla.javascript.Scriptable)
So, for the "reward", I want a good description or working example of
a clean solution to modify/construct a Java class to allow the
newInstance() method to work. Ideally the solution would be entirely
in JavaScript and make only use of Java classes available from Sun's
J2EE and Mozilla's Rhino. A Java source solution that can be invoked
from JavaScript would be okay, as long as you could provide enough of
the solution to show it was viable and not overly fragile to new
versions of Rhino. Web links to FAQs, etc. that get me to the answer
are perfectly valid solutions. |