about java: get `String[].class` from `String.class`, what if `String.class` is a "runtime type"?

watchzerg picture watchzerg · Nov 15, 2012 · Viewed 28k times · Source

Here is a variable Class<?> cls, now I want to get another Array Class Object which component type is cls.

For example, if cls=String.class , I want to get String[].class; if cls=int.class, I want to get int[].class, what should I do?

You see, It's quite easy to get String.class from String[].class:

Class<?> arrayCls = String[].class;
if(arrayCls.isArray()){
    Class<?> cls = arrayCls.getComponentType();
}

But I cannot find easy way to do the reverse.

Here is one possible solution:

Class<?> clazz = String.class;
Class<?> arrayClass = Array.newInstance(clazz,0).getClass();

Is there any batter way to do this please?

Answer

Limeth picture Limeth · Dec 12, 2014

HRgiger's answer improved:

@SuppressWarnings("unchecked")
static <T> Class<? extends T[]> getArrayClass(Class<T> clazz) {
    return (Class<? extends T[]>) Array.newInstance(clazz, 0).getClass();
}

Both of them instantiate an array object when invoked. To get the array type, use

Class<?> childType = ...;
Class<?> arrayType = getArrayClass(childType);