tags:

views:

584

answers:

3
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?

+5  A: 

Just Write

Class ofArray = o.getClass().getComponentType();
sakana
That won't quite work. o is a Long array, not a Long, so I don't think o.getClass() will give what you want.
Herms
yeah you are right. I didn't understand the question. Now it should work.
sakana
+3  A: 

@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!

Daniel Spiewak