Java List First Item getFirstInstanceOf(List source, String className)

Here you can find the source of getFirstInstanceOf(List source, String className)

Description

get First Instance Of

License

Apache License

Declaration

public static Object getFirstInstanceOf(List source, String className) throws ClassNotFoundException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.List;

public class Main {
    public static Object getFirstInstanceOf(List source, String className) throws ClassNotFoundException {
        Class targetInstance = Class.forName(className);
        if (findInstanceOfClassExists(source, className)) {
            for (Object object : source) {

                if (targetInstance.isInstance(object))
                    return targetInstance.cast(object);

            }//from   w ww  . j  a  va 2  s  . co  m
        }
        return null;

    }

    /**
     * check whether the class mentioned does exist in 'list' -- source, return
     * true on first instance
     * 
     * @param source
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    public static boolean findInstanceOfClassExists(List source, String className) throws ClassNotFoundException {
        if (source == null)
            return false;
        if (className == null)
            return false;
        if (source.size() <= 0)
            return false;
        if (className.isEmpty())
            return false;
        Class targetInstance = Class.forName(className);

        for (Object object : source) {
            if (targetInstance.isInstance(object))
                return true;
        }

        return false;

    }
}

Related

  1. getFirstElement(List collection)
  2. getFirstElement(List list)
  3. getFirstElement(List list)
  4. getFirstElementFromList(List list)
  5. getFirstFromList(List list)
  6. getFirstItemOrNull(List items)
  7. getFirstLeaf(List aList)
  8. getFirstNameIndex(List list)
  9. getFirstNonEmptyIndex(final List> list)