简体   繁体   中英

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

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?

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 .

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType() :

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

@ddimitrov is the correct answer. Put into code it looks like this:

public <T> Class<T> testArray(T[] array) {
    return array.getClass().getComponentType();
}

Even more generally, we can test first to see if the type represents an array, and then get its component:

Object maybeArray = ...
Class<?> clazz = maybeArray.getClass();
if (clazz.isArray()) {
    System.out.printf("Array of type %s", clazz.getComponentType());
} else {
    System.out.println("Not an array");
}

A specific example would be applying this method to an array for which the component type is already known:

String[] arr = {"Daniel", "Chris", "Joseph"};
arr.getClass().getComponentType();              // => java.lang.String

Pretty straightforward!

Correct me if im wrong but the [Ltype spec is a defined java standard you can use to figure out the dimensions of a multi dimensional array of type 'type'. Just count the brackets. Yes it's a bit naff compared to the non existent dimensionof operator. Would love to hear if there is amother way. A genric way of specifying a method argument as 'array of indeterminate dimension of T' needed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM