Object[] to Class[] in Java
Is there any built-in Java6 method (perhaps in l开发者_如何学运维ang 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?
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.
In JDK - no. There is in apache commons-lang:
ClassUtils.toClass(Object[] objects)
But writing it yourself isn't painful at all.
I think lambdaj has features for this kind of thing.
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.
精彩评论