Implementing JavaScript index operator in a Java object
A. Sundararajan
sundararajan.athijegannathan at oracle.com
Sun Mar 2 20:37:48 PST 2014
Thanks Andreas.
Hi Tim,
In addition to JSAdapter, there is also
jdk.nashorn.api.scripting.JSObject. Any Java class can implement this
interface to trap get/set indexed/named properties, call/new.
See also
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes
And this interface can also be implemented in script - as usual. See
$nashorn_repo/test/script/basic/JDK-8024847.js as well.
-Sundar
On Saturday 01 March 2014 04:30 PM, Andreas Rieber wrote:
> 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