some nashorn testing

Andreas Rieber rieberandreas at gmail.com
Tue Jan 8 12:30:58 PST 2013


On 08.01.13 19:05, Attila Szegedi wrote:
> On Jan 8, 2013, at 6:22 PM, Andreas Rieber <rieberandreas at gmail.com 
> <mailto: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.
>

I tried some cases and will go for (Nashorn and Rhino):

   var array;
   try {
     array = new (Java.type("java.lang.Object[]"))(len);
   } catch (x) {
     array = [];
   }

The catch block works with Rhino but gives with Nashorn:

Exception in thread "main" java.lang.ClassCastException: Cannot cast 
jdk.nashorn.internal.objects.NativeArray to [Ljava.lang.Object;
     at 
sun.invoke.util.ValueConversions.newClassCastException(ValueConversions.java:461)
     at 
sun.invoke.util.ValueConversions.castReference(ValueConversions.java:456)
     at jdk.nashorn.internal.scripts.Script$main.sprintf(main.js:114)
     at 
jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:350)
     at 
jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:310)
     at 
jdk.nashorn.internal.objects.NativeFunction.apply(NativeFunction.java:133)


cheers
Andreas



More information about the nashorn-dev mailing list