ability to inject custom properties into a JS object

A. Sundararajan sundararajan.athijegannathan at oracle.com
Mon Jun 15 12:53:09 UTC 2015


Please note that nashorn has support to handle Java objects with 'bean 
style' property support. And you could implement Java interfaces and 
extend Java abstract classes in script.  java.util.Map objects are 
treated specially to provide key-value access as properties. 
java.util.ArrayList objects are treated like arrays (indexed element 
access, length property for size). These could be used provide 
script-friendly access to your existing Java classes.

But, if you want to write script "proxies" to trap property access etc., 
then there are two ways:

1) JSAdapter - you'd write JSAdapter wrapper in script.

Example:

https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor

2) Implementing jdk.nashorn.api.scripting.JSObject.

https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/JSObject.html

AbstractJSObject ( 
https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/AbstractJSObject.html 
) provides empty/null implementation for most methods and so you can 
extend it as well.

In addition, any @FunctionalInterface object 
(java.util.functions.Function etc) can be called as a script function. 
So, your script functions could just be Java functional interface objects.

Example:

https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Plugging-inyourownJSObject

Hope this helps,
-Sundar

On Monday 15 June 2015 05:42 PM, Radu Cotescu wrote:
> Hello,
>
> I've recently started looking into replacing Rhino with Nashorn as the
> JavaScript scripting engine for Apache Sling (see SLING-4801 [0]).
>
> Once nice Rhino feature that I don't seem to be able to easily map to
> something from Nashorn is the ability to provide my own object wrappers,
> such that the resulting JS object contains some custom properties. I did
> notice this thread [1] but I wasn't able to reach to a conclusion regarding
> this feature.
>
> Is there a way to easily implement this custom object translation layer
> without having to implement a JSObject? The problem with this approach is
> that Sling script developers will have to use these custom wrapper classes
> (JSObjects) instead of the APIs directly available through the Bindings,
> making scripts written for the Rhino implementation incompatible.
>
> Thanks,
> Radu
>
> [0] - https://issues.apache.org/jira/browse/SLING-4801
> [1] -
> https://www.mail-archive.com/nashorn-dev%40openjdk.java.net/msg01485.html



More information about the nashorn-dev mailing list