using method handles to get array length

21 views
Skip to first unread message

Jochen Theodorou

unread,
Jan 9, 2015, 6:00:53 AM1/9/15
to jvm-la...@googlegroups.com
Hi,

is there a way to get the length of an array using method handles? Of
course I can write a small method to do that, but given the multitude of
primitive types this means a lot of small methods. So I was wondering if
there is a more elegant but still fast solution

bye Jochen

--
Jochen "blackdrag" Theodorou - Groovy Project Tech Lead
blog: http://blackdragsview.blogspot.com/
german groovy discussion newsgroup: de.comp.lang.misc
For Groovy programming sources visit http://groovy-lang.org

Julien Ponge

unread,
Jan 9, 2015, 6:05:20 AM1/9/15
to jvm-la...@googlegroups.com
Hi Jochen,

How about:

lookup.findStatic(Array.class, "getLength", methodType(int.class, Object.class))

(java.lang.reflect.Array)

That's what we use in Golo to provide "length/size" methods to arrays, e.g.:

let a = [1, 2, 3]
println(a: length())

- Julien
> --
> You received this message because you are subscribed to the Google Groups "JVM Languages" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to jvm-language...@googlegroups.com.
> To post to this group, send email to jvm-la...@googlegroups.com.
> Visit this group at http://groups.google.com/group/jvm-languages.
> For more options, visit https://groups.google.com/d/optout.

Jochen Theodorou

unread,
Jan 9, 2015, 6:13:55 AM1/9/15
to jvm-la...@googlegroups.com
Hi Julien,

https://bugs.openjdk.java.net/browse/JDK-8051447 suggests that the
performance of this method is not the best... though it suggest an
equally generic alternative, with which I may go. so thanks for the idea

bye Jochen

Julien Ponge

unread,
Jan 9, 2015, 6:15:54 AM1/9/15
to jvm-la...@googlegroups.com
Otherwise I'd say: generate all Object[] and primitive[] static methods that return you the length, then have method handles to them :-)

Attila Szegedi

unread,
Jan 9, 2015, 8:20:06 AM1/9/15
to jvm-la...@googlegroups.com
Hm. Dynalink (and by extension, Nashorn) uses a method handle to Array.getLength(); maybe I'll rework it this way.
Reply all
Reply to author
Forward
0 new messages