some nashorn testing

Attila Szegedi attila.szegedi at oracle.com
Tue Jan 8 10:05:22 PST 2013


On Jan 8, 2013, at 6:22 PM, Andreas Rieber <rieberandreas at gmail.com> wrote:

> 
> // create Java String array of 5 elements
> var a = java.lang.reflect.Array.newInstance(java.lang.String, 5);
> 

In Nashorn, the expression "java.lang.String" doesn't give you the Class object for String (just as it doesn't do it in Java, in Java you need to write "java.lang.String.class" (or just "String.class" due to autoimport of java.lang in Java); note the ".class"; the name of the type ("java.lang.String") is in Java used for constructor invocation as well as for access to static members - we happen to follow this practice in Nashorn.

In Nashorn, you have several choices. I would suggest using the type() function on the Java built-in object:

  var a = new (Java.type("java.lang.String[]"))(5)

You can find the explanation for integration of Nashorn into the Java type system in the JavaDoc for NativeJava class' type() and extend() methods (I might need to write a blog post about this as it keeps popping up…).

If you expect to instantiate several arrays, it might make sense to do:

  var stringArrayType = Java.type("java.lang.String[]")

  var a = new stringArrayType(5)
  var b = new stringArrayType(10)
  ...


You can keep using the Array.newInstance if you wish, but you'll need to tack .class at the end of java.lang.String:

  var a = java.lang.reflect.Array.newInstance(java.lang.String.class, 5);

should work.

Attila.



More information about the nashorn-dev mailing list