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:Main.java

public static Container findContainer(Component thisComp, Class<? extends Container> containerClass) {
    if (thisComp == null) {
        return null;
    }//from   w w  w  .  j av  a2  s.  c  o  m
    Container parent = thisComp.getParent();
    do {
        parent = parent.getParent();
        if (parent != null && containerClass.isAssignableFrom(parent.getClass())) {
            return parent;
        }
    } while (parent != null);
    return null;
}

From source file:grails.util.GrailsConfig.java

/**
 * Utility method for retrieving a configuration value and performs type checking
 * (i.e. logs a verbose WARN message on type mismatch).
 *
 * @param key the flattened key/*from   w w w  .  j  av  a  2  s .  com*/
 * @param type the required type
 * @param <T> the type parameter
 * @return the value retrieved by ConfigurationHolder.flatConfig
 */
public static <T> T get(String key, Class<T> type) {
    Object o = get(key);
    if (o != null) {
        if (!type.isAssignableFrom(o.getClass())) {
            LOG.warn(String.format("Configuration type mismatch for configuration value %s (%s)", key,
                    type.getName()));
            return null;
        }
        return type.cast(o);
    }
    return null;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.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.
 * //  w  w w  .  ja va  2s . c om
 * @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);
                        boolean equals = false;
                        for (int j = 0; j < l2.size(); j++) {
                            Object el2 = l2.get(j);
                            if (deepCompare(el1, el2)) {
                                if (i == j) {
                                    System.out.println("Values matched at the same index in collections");
                                } else {
                                    System.out.println("Values matched at the different index in collections");
                                }
                                equals = true;
                                break;
                            }
                        }
                        if (!equals) {
                            return false;
                        }
                    }

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

From source file:info.magnolia.cms.util.ServletUtil.java

/**
 * Finds a request wrapper object inside the chain of request wrappers.
 *//*from   w  ww  .ja v a 2 s  .com*/
public static <T extends ServletRequest> T getWrappedRequest(ServletRequest request, Class<T> clazz) {
    while (request != null) {
        if (clazz.isAssignableFrom(request.getClass())) {
            return (T) request;
        }
        request = (request instanceof ServletRequestWrapper) ? ((ServletRequestWrapper) request).getRequest()
                : null;
    }
    return null;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> void addAll(Collection<T> dest, Collection<? super T> src, Class<? extends T> type) {
    if (dest == null || src == null || type == null) {
        throw new IllegalArgumentException("Arguments must not be null.");
    }/*from   www  .j  a v a 2  s  . c o  m*/
    for (Object element : src) {
        if (element != null && type.isAssignableFrom(element.getClass())) {
            dest.add((T) element);
        }
    }
}

From source file:com.xhsoft.framework.common.utils.ReflectUtil.java

/**
 * <p>Description:setFieldValue</p>
 * @param target//from   w  w  w .  j av  a 2 s  .  c  om
 * @param fname
 * @param ftype
 * @param fvalue
 * @return void
 */
@SuppressWarnings("unchecked")
public static void setFieldValue(Object target, String fname, Class ftype, Object fvalue) {
    if (target == null || fname == null || "".equals(fname)
            || (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass()))) {
        return;
    }

    Class clazz = target.getClass();

    try {
        Method method = clazz
                .getDeclaredMethod("set" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), ftype);

        if (!Modifier.isPublic(method.getModifiers())) {
            method.setAccessible(true);
        }

        method.invoke(target, fvalue);

    } catch (Exception me) {
        try {
            Field field = clazz.getDeclaredField(fname);

            if (!Modifier.isPublic(field.getModifiers())) {
                field.setAccessible(true);
            }

            field.set(target, fvalue);
        } catch (Exception fe) {

            if (logger.isDebugEnabled()) {
                logger.debug(fe);
            }
        }
    }
}

From source file:jp.co.ctc_g.jfw.core.util.Classes.java

/**
 * ???????????????/*from w ww  .j  a va  2 s .  com*/
 * ?????????
 * ??????
 * <pre class="brush:java">
 * Classes.howFar(Object.class, Object.class); // 0
 * Classes.howFar(String.class, Object.class); // 1
 * Classes.howFar(JPanel.class, Object.class); // 4
 * Classes.howFar(JPanel.class, JComponent.class); // 1
 * </pre>
 * ?????????<code>-1</code>?????
 * @param from ??
 * @param to ??
 * @return ??
 */
public static int howFar(Class<?> from, Class<?> to) {
    Args.checkNotNull(from);
    Args.checkNotNull(to);
    if (from == to)
        return 0;
    if (!to.isAssignableFrom(from))
        return -1;
    int distance = 0;
    Class<?> hierarchyExplorer = from;
    while (hierarchyExplorer != null && hierarchyExplorer != to) {
        hierarchyExplorer = hierarchyExplorer.getSuperclass();
        if (hierarchyExplorer != null) {
            distance++;
        } else {
            // ???????????????
            assert false;
        }
    }
    return distance;
}

From source file:Main.java

private static <T extends View> T getFirstChildByInstance(ViewGroup parent, Class<T> instance) {
    View retView = null;// w ww. j a v  a  2 s . com
    int childCount = parent.getChildCount();

    for (int childIndex = 0; childIndex < childCount; childIndex++) {
        View child = parent.getChildAt(childIndex);

        if (instance.isAssignableFrom(child.getClass())) {
            return instance.cast(child);
        }

        if (child instanceof ViewGroup) {
            View v = getFirstChildByInstance((ViewGroup) child, instance);

            if (v != null) {
                return instance.cast(v);
            }
        }
    }

    return instance.cast(retView);
}

From source file:com.yahoo.bard.webservice.util.Utils.java

/**
 * Given a collection of objects which share the same super class, return the subset of objects that share a common
 * sub class./* ww  w .j a  v a 2 s.c  om*/
 *
 * @param set  Input set
 * @param <T> Input set type
 * @param type  sub class
 * @param <K> sub class type
 *
 * @return ordered subset of objects that share a common sub class
 */
public static <T, K extends T> LinkedHashSet<K> getSubsetByType(Collection<T> set, Class<K> type) {
    return set.stream().filter(member -> type.isAssignableFrom(member.getClass()))
            .map(StreamUtils.uncheckedCast(type)).collect(Collectors.toCollection(LinkedHashSet::new));
}

From source file:at.molindo.utils.reflect.ClassUtils.java

/**
 * @return <code>true</code> if <code>cls</code> is assignable to at least
 *         one class in <code>classes</code>
 *///from   ww  w.j a va2s . c  o  m
public static boolean isAssignable(Class<?> cls, Set<Class<?>> classes) {
    if (cls == null || classes.isEmpty()) {
        return false;
    }
    for (Class<?> c : classes) {
        if (c.isAssignableFrom(cls)) {
            return true;
        }
    }
    return false;
}