Java Collection Element Get getClassFromCollection(Collection collection)

Here you can find the source of getClassFromCollection(Collection collection)

Description

Finds a class type that is in the containing collection, will always return something (failsafe to Object.class)

License

Apache License

Parameter

Parameter Description
collection any collection (List, Set, etc.)

Return

the class type contained in this collecion

Declaration

@SuppressWarnings("unchecked")
public static Class<?> getClassFromCollection(Collection collection) 

Method Source Code

//package com.java2s;
/**/*from   w  ww.  j  a  va  2 s  . co m*/
 * $Id: ClassLoaderUtils.java 2 2008-10-01 10:04:26Z azeckoski $
 * $URL: http://reflectutils.googlecode.com/svn/trunk/src/main/java/org/azeckoski/reflectutils/ClassLoaderUtils.java $
 * ClassLoaderUtils.java - genericdao - May 8, 2008 5:39:34 PM - azeckoski
 **************************************************************************
 * Copyright (c) 2008 Aaron Zeckoski
 * Licensed under the Apache License, Version 2.0
 * 
 * A copy of the Apache License has been included in this 
 * distribution and is available at: http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Aaron Zeckoski (azeckoski@gmail.com) (aaronz@vt.edu) (aaron@caret.cam.ac.uk)
 */

import java.util.Collection;

public class Main {
    /**
     * Finds a class type that is in the containing collection,
     * will always return something (failsafe to Object.class)
     * @param collection any collection (List, Set, etc.)
     * @return the class type contained in this collecion
     */
    @SuppressWarnings("unchecked")
    public static Class<?> getClassFromCollection(Collection collection) {
        // try to get the type of entities out of this collection
        Class<?> c = Object.class;
        if (collection != null) {
            if (!collection.isEmpty()) {
                c = collection.iterator().next().getClass();
            } else {
                // this always gets Object.class -AZ
                //c = collection.toArray().getClass().getComponentType();
                c = Object.class;
            }
        }
        return c;
    }
}

Related

  1. getByIndex(Collection vals, int idx)
  2. getByMostFrequent(Collection collection)
  3. getCardinalityMap(final Collection col)
  4. getCardinalityMap(final Collection coll)
  5. getCaseInsensitive(Collection data, String needle)
  6. getClosest(final String pattern, Collection targets)
  7. getCollection(final Iterable iterable)
  8. getCollection(final String iText, final int iStartPosition, final Collection iCollection)
  9. getCollection(Object entity)