Wednesday, December 31, 2008

Retrieving an Array's Class Using the Component Type

Recently I needed to implement a method that returns class of an array based on its component type. E.g. for String.class, the method should return String[].class.

I tried to google, but the results were quite disappointing: it appears that none of the java.lang.reflect.* classes provides such a functionality. So I did a workaround:

public static Class<?> getArrayClassByComponentType(Class<?> ctype) {
return Array.newInstance(ctype, 0).getClass();
}

As you can see, I create a temporary array of size zero and return its class. Since arrays always have a default constructor, it will always work.

I'm still interested to know, if there is more elegant solution...

No comments: