Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object[] to Class[] in Java

Tags:

java

Is there any built-in Java6 method (perhaps in lang or reflection?) for performing:

private Class[] getTypes(final Object[] objects) {
    final Class[] types = new Class[objects.length];
    for (int i = 0; i < objects.length; i++) {
        types[i] = objects[i].getClass();
    }
    return types;
}

Which takes an Object array and returns an array containing the type of each element?

like image 380
Robert Campbell Avatar asked Feb 02 '10 08:02

Robert Campbell


2 Answers

No, there's no built-in facility for this in JavaSE.

Not much of a burden, surely, it's easily unit-testable and only a few lines.

If you really wanted something you don't write yourself, there are various 3rd-party libraries that will do it for you (e.g. Apache Commons Lang's ClassUtils, CGLIB's ReflectUtils), so if you already have one of those, you can use them.

like image 111
skaffman Avatar answered Oct 29 '22 00:10

skaffman


In JDK - no. There is in apache commons-lang:

ClassUtils.toClass(Object[] objects)

But writing it yourself isn't painful at all.

like image 29
Bozho Avatar answered Oct 29 '22 01:10

Bozho