Java List Cast castTo(final List list, final Class clasz)

Here you can find the source of castTo(final List list, final Class clasz)

Description

cast To

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    public static <E> List<E> castTo(final List<?> list, final Class<E> clasz) 

Method Source Code

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

import java.util.Collection;

import java.util.List;

public class Main {
    @SuppressWarnings("unchecked")
    public static <E> List<E> castTo(final List<?> list, final Class<E> clasz) {
        if (isOf(list, clasz)) {
            return (List<E>) list;
        }//from   ww  w.  j a v  a 2  s.  c  o  m
        throw new IllegalArgumentException("List contains invalid type.");
    }

    private static <E> boolean isOf(final Collection<?> collection, final Class<E> clasz) {
        if (null == collection) {
            return false;
        }
        for (Object o : collection) {
            if (null != o && !clasz.isInstance(o)) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. castList(List list, Class clazz)
  2. castListElem(List list, V target)
  3. castListUnchecked(Object list)
  4. castNonNullListParameterTo(String parameterName, List value, Class requiredType)
  5. castOrCopyToList(Iterable iterable)
  6. castToDocumentList(Object obj)
  7. castToList(U[] array, Class clazz)
  8. castToStringList(Object value)
  9. IS_CASTABLE_LIST(Class className, Object obj)