Java access in Rhino JavaScript engine can be used to get soft, weak references in scripts. For example, we may define the following script wrappers:
Object.prototype.softRef = function() {
return new java.lang.ref.SoftReference(this);
}
Object.prototype.weakRef = function() {
return new java.lang.ref.WeakReference(this);
}
Because we have added function properties to Object.prototype, we can create soft, weak references of any script object as shown below:
var x = "hello";
// create a SoftReference of script String 'hello'
x = x.softRef();
// may get null or "hello" depending on whether
// the SoftReference is cleared or not
x.get();
Java overloaded method calls are resolved are resolved at compile time (i.e., static resolution). But, when you call Java methods from JavaScript, the overload resolution occurs at runtime. JavaScript method overload resolution is explained in LiveConnect 3 document. In most cases, the expected method is called. Sometimes, you may want to force the choice and choose a particular method. For example, you may want to call a specific println() method of java.io.PrintStream class. For such scenarios, you can explicitly specify the method to be invoked.
Note that in JavaScript, object members are accessed in two forms:
var out = java.lang.System.out;
out.println("hello world"); // calls PrintStream.println(java.lang.Object)
out['println(double)'](13); // calls PrintStream.println(double)
The second member access form is useful in other scenarios as well. For example, when JavaScript reserved word is used as field/method name of an object:
// store System input stream in a variable
var s = java.lang.System.in; // This does not work!
You get the following error in jrunscript
// in is a keyword in JavaScript and therefore can not be used
// as field name, but the following works:
var s = java.lang.System["in"];