CounterFlame CounterFlame - 11 months ago 51
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) {
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())) {
// ClassCastException thrown here
} catch (IllegalAccessException e) {
// Should not occur with setAccessible(true), return false just
// in case
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 Source

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