How to get the Array Class for a given Class in Java?

Since Java 12

Class provides a method arrayType(), which returns the array type class whose component type is described by the given Class. Please be aware that the individual JDK may still create an instance of that Class³.

Class<?> stringArrayClass = FooBar.arrayType()

Before Java 12

If you don’t want to create an instance, you could create the canonical name of the array manually and get the class by name:

// Replace `String` by your object type.
Class<?> stringArrayClass = Class.forName(
    "[L" + String.class.getCanonicalName() + ";"
);

But Jakob Jenkov argues in his blog that your solution is the better one, because it doesn’t need fiddling with strings.

Class<?> stringArrayClass = Array.newInstance(String.class, 0).getClass();

³ Thanks for the hint to Johannes Kuhn.

Leave a Comment