CounterFlame CounterFlame - 19 days ago 5
Java Question

Reflection - inherited fields all null or empty

I have a class (with superclass) for which I want to check that all fields are either NULL, or if it's a Collection, that it's empty. With the following code I am able to check for NULL and whether it's a Collection, but I can't seem to cast the Collection to check it's size:

public static boolean objectIsEmpty(Object object) {
for (Class<?> c = object.getClass(); c != null; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
if (field.get(object) != null) {
if (field.getType().equals(List.class)) {
// System.err.println("len " +
// Array.getLength(field.get(object)));
}
if (Collection.class.isAssignableFrom(field.getType())) {
System.err.println(Collection.class.cast(field).size());
// ClassCastException thrown here
}
}
} catch (IllegalAccessException e) {
// Should not occur with setAccessible(true), return false just
// in case
e.printStackTrace();
return false;
}
}
}
return true;


But that results in java.lang.ClassCastException: Cannot cast java.lang.reflect.Field to java.util.Collection

How do I get the size of the Lists?

Answer

You cannot cast field to collection. You can cast the field object to collection. Try this:

System.err.println(Collection.class.cast(field.get(object)).size());
Comments