Implementing JavaScript index operator in a Java object

Andreas Rieber rieberandreas at gmail.com
Sat Mar 1 03:00:03 PST 2014


Hi Tim,

this is possible with JSAdapter described in [1].

Short sketch could look like this:

---
var myobj = (function () {

     return new JSAdapter() {
         __get__: function(name) {
             print("getter called for '" + name + "'"); return name;
         },

         __put__: function(name, value) {
             print("setter called for '" + name + "' with " + value);
         }
     }
})();

myobj.x;
myobj.x = 12;
myobj[3];
---
output:

getter called for 'x'
setter called for 'x' with 12
getter called for '3'
---

happy scripting
Andreas

[1] https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions


On 01.03.2014 10:27, Tim Fox wrote:
> Hello Nashorn folks,
>
> I have a JavaScript object, and I'd like to 'override' what the index 
> operator [] does on it.
>
> I.e. when I do
>
> var x = myobj[3];
>
> I actually want it to call some other function on the object, e.g.
>
> myobj.get(3);
>
> I'm pretty sure this isn't possible in pure JS, so I was thinking of 
> wrapping a Java Object as a JavaScript object, e.g. if I have
>
> public class MyJavaClass {
>    public Object get(int index) {
>       ...
>       return something;
>    }
> }
>
> I would like to have a JS wrapper for it, such that when I call:
>
> var x = myJavaWrapper[3];
>
> It actually calls:
>
> myJavaObject.get(3);
>
> Is this possible in Nashorn?



More information about the nashorn-dev mailing list