I have a Class
variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this:
Class arrayOfFooClass = java.lang.reflect.Array.newInstance(fooClass, 0).getClass();
Is there a way to do this without creating the new instance?
The Arrays class in java. util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class.
Step 1: Traverse the array. Step 2: Match the key element with array element. Step 3: If key element is found, return the index position of the array element. Step 4: If key element is not found, return -1.
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.
Since Java 12, there is the arrayType()
method on java.lang.Class. With that:
Class<?> arrayOfFooClass = fooClass.arrayType();
The implementation of Class.arrayType()
just calls Arrays.newInstance(this, 0).getClass()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With