« October 2005 »
SunMonTueWedThuFriSat
      
1
2
3
4
8
9
10
11
12
13
15
16
17
19
22
23
27
28
30
31
     
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 986

Powered by Roller Weblogger.
« Previous day (Oct 22, 2005) | Main | Next day (Oct 24, 2005) »
20051024 Monday October 24, 2005

Weak references in JavaScript

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(); 





( Oct 24 2005, 06:42:42 PM IST ) Permalink Comments [2] del.icio.us | furl | simpy | slashdot | technorati | digg

Java overloaded method resolution in JavaScript

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:

  1. object.<field-name>
  2. object[field-name-as-string] (or object[index] if field is indexed)
We use the second form to specify explicit method to invoke as shown below:


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
js> var s = java.lang.System.in
script error: sun.org.mozilla.javascript.internal.EvaluatorException: missing name after . operator (#1) in at line number 1


// 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"];




( Oct 24 2005, 09:34:13 AM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

Copyright (C) 2005, A. Sundararajan's Weblog