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.
}
}
}