Search code examples
javadata-structurescollectionsis-empty

Java global isEmpty() method


I have an application which uses code that produces various types of objects and data structures, returning them as Object instances, and would like a generic way of establishing whether any of those objects is "empty" (or null).

(This is not a matter of design, or of whether such a method should be used, but a question of optimizing the solution to an existing requirement.)

So, here is a simple go:

public static boolean isEmpty(Object content)
{
    if (content == null)
    {
        return true;
    }
    else if (content instanceof CharSequence)
    {
        return (((CharSequence)content).length() == 0);
    }
    else if (content instanceof Collection<?>)
    {
        return ((Collection<?>)content).isEmpty();
    }
    else if (content instanceof Object[])
    {
        return (((Object[])content).length == 0);
    }
    else  // Use reflection (an exaggeration, for demo purposes)
    {
        try
        {
            Method isEmpty = content.getClass().
                             getDeclaredMethod("isEmpty", (Class<?>[])null);
            if (isEmpty != null)
            {
                Object result = isEmpty.invoke(content, (Object[])null);

                if (result instanceof Boolean)
                {
                    return (Boolean)result;
                }
            }
        }
        catch (Exception e)
        {
        }
    }

    return false;
}

Any ideas for potential improvements, in terms of either performance, or coverage?

For instance, reflection could be also used to establish whether the object has a length() or size() method, invoke it and see if the result is 0. (In reality, reflection is probably too much, but I am including it here for completeness.)

Is there a top-level class very commonly used, which has a length() or size() method, instead of the isEmpty() method, to include in the above case, similarly to Collection that has isEmpty()?


Solution

  • Instead of the ugly instanceofs, split up the method into several methods with the same name but different args. e.g.

    static boolean isEmpty(Object[] array)
    static boolean isEmpty(Collection collection)
    static boolean isEmpty(CharSequence cs)
    

    Instead of reflection, if you really want your own interface for special objects, declare that interface, and then, for consistency with the above, offer the static utility

    static boolean isEmpty(IMayBeEmpty imbe);