Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the array Class of a component type

Tags:

java

arrays

If I have an instance of Class, is there a way of obtaining a Class instance for its array type? What I'm essentially asking for is the equivalent of a method getArrayType which is the inverse of the getComponentType() method, such that:

array.getClass().getComponentType().getArrayType() == array.getClass() 
like image 226
Tom Castle Avatar asked Feb 04 '11 17:02

Tom Castle


People also ask

How do you find the type of an array?

Well, you can get the element type of the array: Type type = array. GetType(). GetElementType();

How do you take an array from a class?

Syntax: Class_Name obj[ ]= new Class_Name[Array_Length]; For example, if you have a class Student, and we want to declare and instantiate an array of Student objects with two objects/object references then it will be written as: Student[ ] studentObjects = new Student[2];

Which method is provided by array class to search an element in an array?

Arrays class provides both sort() and binarySearch() for first sorting an array and than performing binary search on it. Arrays. binarySearch() method returns >=0 if it finds elements in Array.

What is the array class?

The Array class is the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language. An element is a value in an Array.


1 Answers

One thing that comes to mind is:

java.lang.reflect.Array.newInstance(componentType, 0).getClass(); 

But it creates an unnecessary instance.

Btw, this appears to work:

Class clazz = Class.forName("[L" + componentType.getName() + ";"); 

Here is test. It prints true:

Integer[] ar = new Integer[1]; Class componentType = ar.getClass().getComponentType(); Class clazz = Class.forName("[L" + componentType.getName() + ";");  System.out.println(clazz == ar.getClass()); 

The documentation of Class#getName() defines strictly the format of array class names:

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting.

The Class.forName(..) approach won't directly work for primitives though - for them you'd have to create a mapping between the name (int) and the array shorthand - (I)

like image 91
Bozho Avatar answered Oct 17 '22 19:10

Bozho