Example usage for java.lang Class isAssignableFrom

List of usage examples for java.lang Class isAssignableFrom

Introduction

In this page you can find the example usage for java.lang Class isAssignableFrom.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isAssignableFrom(Class<?> cls);

Source Link

Document

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

Usage

From source file:edu.duke.cabig.c3pr.utils.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * //from   w  w  w. jav a  2 s .  c  o  m
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        Object el2 = l2.get(i);
                        if (!deepCompare(el1, el2)) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:com.dsh105.commodus.Affirm.java

public static void checkInstanceOf(Class<?> type, Object instance, boolean allowNull) {
    Affirm.notNull(type);/*w  ww.j a va 2 s .  co m*/
    if (!allowNull) {
        Affirm.notNull(instance);
    }
    if (!type.isAssignableFrom(instance.getClass())) {
        throwException(new IllegalStateException(
                instance.getClass().getCanonicalName() + " must be a subclass of " + type.getCanonicalName()));
    }
}

From source file:jfix.util.Reflections.java

/**
 * Returns true if given class can be assigned to given field (which might
 * be a simple field or array).//from w w  w .  ja v  a  2 s.  com
 */
public static boolean isAssignable(Class<?> clazz, Field field) {
    return clazz.isAssignableFrom(field.getType())
            || (field.getType().isArray() && clazz.isAssignableFrom(field.getType().getComponentType()));
}

From source file:Main.java

static boolean isTypeAssignableFrom(Type type, Class<?> clazz) {
    Class<?> aClazz = null;
    try {//from w w w.  j av a  2s. c  o  m
        aClazz = getClass(type);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    if (aClazz != null && clazz.isAssignableFrom(aClazz)) {
        return true;
    }
    return false;
}

From source file:net.servicefixture.converter.ObjectConverter.java

public static net.servicefixture.converter.Converter lookUpConverter(Class type) {
    if (converters.containsKey(type)) {
        return (net.servicefixture.converter.Converter) converters.get(type);
    }/* w w w. j  av  a2 s  .c  om*/
    //Otherwise, let's check if any super class of type has a converter.
    for (Iterator iter = converters.keySet().iterator(); iter.hasNext();) {
        Class<?> clazz = (Class<?>) iter.next();
        if (clazz.isAssignableFrom(type)) {
            return (net.servicefixture.converter.Converter) converters.get(clazz);
        }
    }
    return null;
}

From source file:com.wcs.base.util.ArrayUtils.java

/**
 *
 * @param c1/*from  w w  w  .  j av a2 s .  c  om*/
 * @param c2
 * @return
 *
 */
public static Class commonClass(Class c1, Class c2) {
    if (c1 == c2) {
        return c1;
    }

    if ((c1 == Object.class) || c1.isAssignableFrom(c2)) {
        return c1;
    }

    if (c2.isAssignableFrom(c1)) {
        return c2;
    }

    if (c1.isPrimitive() || c2.isPrimitive()) {
        throw new IllegalArgumentException("incompatible types " + c1 + " and " + c2);
    }

    return Object.class;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <S, D extends S> D[] downcastToArray(Collection<S> source, Class<D> destClass) {
    D[] dest = (D[]) Array.newInstance(destClass, source.size());
    Iterator<S> it = source.iterator();
    for (int i = 0; i < dest.length; i++) {
        S s = it.next();// w  w  w  . ja  v a  2 s .c om
        if (destClass.isAssignableFrom(s.getClass()))
            dest[i] = (D) s;
        else
            throw new IllegalArgumentException("Could not downcast element from class "
                    + s.getClass().getSimpleName() + " to " + destClass.getSimpleName());
    }
    return dest;
}

From source file:com.google.code.guice.repository.spi.TypeUtil.java

private static <T> Class<T> findAppropriateType(Iterable<Type> types, Class<T> genericParameterClass) {
    for (Type type : types) {
        if (type instanceof Class && genericParameterClass.isAssignableFrom((Class<?>) type)) {
            return (Class) type;
        }/*  www  .  ja v a 2s  .  c  om*/
    }
    return null;
}

From source file:ca.uhn.fhir.util.ReflectionUtil.java

@SuppressWarnings("unchecked")
public static <T> T newInstanceOrReturnNull(String theClassName, Class<T> theType) {
    try {/*from  w w  w  .j a  va 2 s  .c o m*/
        Class<?> clazz = Class.forName(theClassName);
        if (!theType.isAssignableFrom(clazz)) {
            throw new ConfigurationException(theClassName + " is not assignable to " + theType);
        }
        return (T) clazz.newInstance();
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        ourLog.info("Failed to instantiate {}: {}", theClassName, e.toString());
        return null;
    }
}

From source file:Main.java

/**
 * Gets the elements of received type within the received list.
 * //from  ww  w  . j a v  a  2s.  c  om
 * @param pList
 *            the list
 * @param pType
 *            the type to search for
 * 
 * @return the elements of the received type
 */
@SuppressWarnings("unchecked")
public static <C> List<C> getElementsOfType(final Collection<?> pList, final Class<C> pType) {
    final List<C> list = new ArrayList<C>();

    if (pList != null && pList.size() > 0) {
        synchronized (pList) {
            for (final Object obj : pList) {
                if (pType.isAssignableFrom(obj.getClass())) {
                    list.add((C) obj);
                }
            }
        }
    }

    return list;
}