Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how do I dynamically determine the type of an array?

Tags:

java

Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ??? 

Running the first 3 lines emits;

true [Ljava.lang.Long; 

How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?

like image 692
Bob Herrmann Avatar asked Oct 17 '08 16:10

Bob Herrmann


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

Which classes in Java is used to implement a dynamic array?

Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

Does Java have dynamic arrays?

Introduction to Dynamic Array in JavaThe dynamic array is such a type of an array with a huge improvement for automatic resizing. The only limitation of arrays is that it is a fixed size. This translates into a meaning that you can only specify the number of elements that your array can hold ahead of time.


1 Answers

Just write

Class ofArray = o.getClass().getComponentType(); 

From the JavaDoc:

public Class<?> getComponentType()

Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.

like image 135
sakana Avatar answered Sep 20 '22 16:09

sakana