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()
Well, you can get the element type of the array: Type type = array. GetType(). GetElementType();
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];
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.
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.
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
)
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