What's the best way to get a Class object for an array type?
It's easy to get a class literal for a class:
String.class
But how can I get a class object for an array type?
This works, but it's ugly, and probably not a compile time constant:
new byte[0].getClass()
I looked in the JLS but the only thing I found out is that what I'm calling a "class literal" isn't a "literal" according to the JLS definition.
You can still use a class literal, even for an array type. This compiles just fine.
Class<String[]> clazz = String[].class;
Class<byte[]> clazz2 = byte[].class;
Section 15.8.2 of the JLS states:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type
void
, followed by a '.' and the tokenclass
.
(bold emphasis mine)
You can simply type
Class<?> clazz = byte[].class;