How can I tell what type of class is inside a Collection? I need to handle simple data types differently than complex types and therefore I must know the contained class. At the moment, I have to iterate through the collection to find out the class which doesn’t sound right. This link was quite helpful but didn’t fully address my issue. Basically, here are the questions:
1. How to determine the class inside the collection?
2. how can I tell if the object is a java wrapper class (Integer, String, Date, etc..) or a proprietary class (Student, Vehicle, etc…).
Thank you
Jabawaba
entity = new SomeObject();
Class entityClass = entity.getClass();
for (Method method : entityClass.getDeclaredMethods()) {
Class<?> returnType = method.getReturnType();
if (returnType != null) {
if (returnType.isPrimitive() || (returnType.getName().startsWith("java.lang.")) || (returnType == java.util.Date.class)) {
// handling primitive and wrapper classes
handleScalar(method);
} else if (Collection.class.isAssignableFrom(returnType)) {
Collection collection = (Collection) method.invoke(entity);
if (collection == null || collection.isEmpty()) {
continue;
}
for (Object value : collection) {
if (value.getClass().getName().startsWith("java.lang.") || (value.getClass() == java.util.Date.class)) {
handleSimpleVector(method);
// no need to go through all the simple values
continue;
} else {
// Each 'value' is itself a complex object.
handleComplexObject(method);
}
}
} else if (<return-type-is-an-Array>){
// do something similar as the above.
}
}
}
1) You simply can’t if it’s not a generically typed Collection. Non-typed Collections can contain any mixture of object types.
If you’re dealing with a (non-empty) typed Collection, then you could determine the class of its contents at runtime e.g. by
There’s no other way to determine the generic type information at runtime since the generic type is purely compile-time information.
2) Date is not a wrapper class – the primitive classes and their wrappers are:
You can determine whether your class is a primitive one using Class#isPrimitive. Note, however, that this will only determine whether an object is really primitive, it will not determine whether you are dealing with an autoboxed value:
But, every wrapper class declares a field named “TYPE” that represents the primitive class it is wrapping. So you can check whether a class is a wrapper class like this: