Friday, March 7, 2008

You CAN access Java objects from MS JScript

Until now, I thought you could only instantiate Java objects from within JavaScript (aka ECMAScript), but not from JScript (Microsoft's version of JavaScript, which is slightly different). But today I found out how to create Java objects within JScript.

You can create Java objects using the GetObject(moniker) method, specifying a "moniker" that is "java:class_name_to_instantiate". For example, to create a Java Date object, you can use:

var mydate = GetObject("java:java.util.Date");
// then you can print the value

In JavaScript/ECMAScript (under the Rhino engine at least), the above can be accomplished with the importClass() function. For example:

var mydate = new File("C:/myfile");

An important difference in functionality between the two, however, is that I cannot find any way in JScript to invoke a class constructor method with any arguments. For example, the following will NOT work:

var myfile = GetObject("'c:/myfile')");

The workaround I see for this limitation is:

1. Create your own Java class that has a constructor that requires no parameters.

2. In this class, define methods to create the types of objects you need.

3. After compiling your class, you will need to place the .class file into your %WINDOWS%\java\truslib folder.

You can get more information about the other supported monikers, and the GetObject function in general, at

No comments: