"not an object"
Sundararajan Athijegannathan
sundararajan.athijegannathan at oracle.com
Wed Jun 1 04:40:38 UTC 2016
Hi,
Java objects are treated "as is" in nashorn. i.e., Nashorn uses
wrapperless Java object access. So, Java objects are *not* ECMAScript
objects. Dynamic property addition, prototype manipulation etc. won't
work on Java objects.
But, you can create a helper ECMAScript object whose properties are
bound to the properties of a Java object. You can use
Object.bindProperties extension for this [
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties
]
Example:
var props = java.lang.System.properties;
var obj = Object.bindProperties({}, props); // create a new script
object and bind it's properties to that of Java object
Object.getOwnPropertyNames(obj).forEach(function(val) { print(val) });
Note that Java Maps are treated as 'special' in that keys can be used as
properties. [
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JavaMapkeysasproperties
]
That also could be used to provide script friendly return object from
your Java code.
Hope this helps,
-Sundar
On 6/1/2016 1:53 AM, yikes aroni wrote:
> So from a javascript function i call a java method that returns a java
> object. What gets returned is not a simple bean. It has properties and
> methods on it.
>
> var xxx = MyJavaClass.getMeSomething();
>
> The *typeof* xxx is "object" according to Nashorn. However, when i try to
> do things with it -- as if it were a Javascript object -- I get the message
>
> TypeError: testSample is not an Object
>
> Is there something specific i need to do to be able to manipulate xxx as a
> javascript object? For example, I want to be able to add properties and
> functions to it
>
> xxx['someProp'] = 3.14;
> xxx['someFn'] = function() {
> print('hello!');
> }
>
> I want to be able to get stuff from it
>
> Object.getOwnPropertyNames(xxx).forEach(function(val) { print(val) });
>
> Stuff like that... but i can't because it's not seen as a native JS
> "object"
>
> thanks. I hope i am clear.
More information about the nashorn-dev
mailing list