Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 940
Deepak Sarda Avatar asked Nov 05 '09 09:11

Deepak Sarda


People also ask

What is the class of an array in Java?

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.

How do you search an array for a specific element in Java?

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.


2 Answers

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.

like image 74
Christian Strempfer Avatar answered Oct 13 '22 04:10

Christian Strempfer


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().

like image 44
Johannes Kuhn Avatar answered Oct 13 '22 03:10

Johannes Kuhn