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

3 Answers 3

93

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.

Sign up to request clarification or add additional context in comments.

Comments

22

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

Comments

6

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

3 Comments

What if first element is null i.e. String[] arr = {null, "Chris", "Joseph"};
@Psycho, doesn't matter null or not null, all these solution use reflection which is based on the stored meta-info about the class that (might) be available at runtime. Reflection is usually illegal access to the class meta-info and in some cases we might not be allowed to use it...
seems like better solution would be to check if array.length is zero first and return, if non-zero, then check the first element's type and get the type info, This doesn't use Reflection. However if the dev still want's to know the type info of an empty array, then it seems like reflection is the only option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.