Robert Campbell
Robert Campbell

Reputation: 6958

Object[] to Class[] in 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?

Upvotes: 5

Views: 226

Answers (4)

Bozho
Bozho

Reputation: 597114

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

ClassUtils.toClass(Object[] objects)

But writing it yourself isn't painful at all.

Upvotes: 2

Itay Maman
Itay Maman

Reputation: 30723

No, there's no better way to do that. However, I don't think it matters much. You already packaged your code as a reusable method. If you need to use it from several distinct classes just turn into a public static method in some utility class.

Once you've done that then, for all practical purposes, you have a convenient way for converting ab array of object into an array of classes. In other words, if you already implemented a certain service in a reusable way, then you effectively extended your toolkit. It does not matter that this specific service is not part of "standard" JRE.

Upvotes: 1

skaffman
skaffman

Reputation: 403501

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.

Upvotes: 5

jqno
jqno

Reputation: 15520

I think lambdaj has features for this kind of thing.

Upvotes: 1

Related Questions