Skip to content
Advertisement

Getting the class of the components of an array

If I have

JavaScript

how can I get T.class from array?

If I do array.getClass() that gets me T[].class instead.

Advertisement

Answer

Component Type

Use this:

JavaScript

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

Reference:


Safe / Unsafe casting

Is there a way I can cast to Class from Class returned by getComponentType() without getting a compiler warning?

take this method:

JavaScript

Here’s the generated byte code:

JavaScript

As you can see, the parameter type is erased to Object[], so the compiler has no way to know what T is. Yes, the compiler could use array.getClass().getComponentType(), but that would sometimes fail miserably because you can do stuff like this:

JavaScript

(In this case array.getClass().getComponentType() returns String.class, but T stands for Integer. Yes, this is legal and does not generate compiler warnings.)

Advertisement