Example usage for java.lang Class isInstance

List of usage examples for java.lang Class isInstance

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInstance(Object obj);

Source Link

Document

Determines if the specified Object is assignment-compatible with the object represented by this Class .

Usage

From source file:Main.java

/**
 * Returns a list of objects of <code>expectedType</code> contained in the given <code>collection</code>. Any
 * objects in the collection that are not assignable to the given <code>expectedType</code> are filtered out.
 * <p>//from w  ww . j a v a  2 s .c  om
 * The order of the items in the list is the same as the order they were provided by the collection. The given
 * <code>collection</code> remains unchanged by this method.
 * <p>
 * If the given collection is null, en empty list is returned.
 *
 * @param collection   An iterable (e.g. Collection) containing the unfiltered items.
 * @param expectedType The type items in the returned List must be assignable to.
 * @param <T>          The type items in the returned List must be assignable to.
 * @return a list of objects of <code>expectedType</code>. May be empty, but never <code>null</code>.
 */

public static <T> List<T> filterByType(Iterable<?> collection, Class<T> expectedType) {
    List<T> filtered = new LinkedList<>();
    if (collection != null) {
        for (Object item : collection) {
            if (item != null && expectedType.isInstance(item)) {
                filtered.add(expectedType.cast(item));
            }
        }
    }
    return filtered;
}

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

/**
 * Given a RuntimeException, this method will:
 * - throw its cause exception, if the cause exception is an instance of the type of the unwrapIf parameter
 * - throw its cause exception, if the cause exception is a RuntimeException
 * - throw the given RuntimeException otherwise.
 *//*from  w  ww  .j  a  v a2  s  . com*/
public static <E extends Throwable> void unwrapIf(RuntimeException e, Class<E> unwrapIf) throws E {
    final Throwable wrapped = e.getCause();
    if (unwrapIf != null && unwrapIf.isInstance(wrapped)) {
        throw (E) wrapped;
    } else if (wrapped != null && wrapped instanceof RuntimeException) {
        throw (RuntimeException) wrapped;
    } else {
        throw e;
    }
}

From source file:com.qwazr.utils.ExceptionUtils.java

@SuppressWarnings("unchecked")
public static <T extends Exception> T throwException(Exception exception, Class<T> exceptionClass) throws T {
    if (exception == null)
        return null;
    if (exceptionClass.isInstance(exception))
        throw (T) exception;
    try {/* ww  w. j  a v a  2 s.  c  om*/
        return exceptionClass.getConstructor(Exception.class).newInstance(exception);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Find a value of the given type in the given collection.
 * @param coll the collection to search//from  w ww.ja  v  a 2 s  .  c  o m
 * @param type the type to look for
 * @return a value of the given type found, or <code>null</code> if none
 * @throws IllegalArgumentException if more than one value
 * of the given type found
 */
public static Object findValueOfType(Collection<?> coll, Class<?> type) throws IllegalArgumentException {
    Object value = null;
    for (Iterator<?> it = coll.iterator(); it.hasNext();) {
        Object obj = it.next();
        if (type.isInstance(obj)) {
            if (value != null) {
                throw new IllegalArgumentException(
                        "More than one value of type [" + type.getName() + "] found");
            }
            value = obj;
        }
    }
    return value;
}

From source file:Main.java

/**
 * An improved version of/*  ww w  .jav a 2s. c  o  m*/
 * {@link SwingUtilities#getAncestorOfClass(Class, Component)}. This method
 * traverses {@code JPopupMenu} invoker and uses generics to return an
 * appropriately typed object.
 * 
 * @param <T>
 *            the type of ancestor to find
 * @param clazz
 *            the class instance of the ancestor to find
 * @param c
 *            the component to start the search from
 * @return an ancestor of the correct type or {@code null} if no such
 *         ancestor exists. This method also returns {@code null} if any
 *         parameter is {@code null}.
 */
@SuppressWarnings("unchecked")
public static <T> T getAncestor(Class<T> clazz, Component c) {
    if (clazz == null || c == null) {
        return null;
    }

    Component parent = c.getParent();

    while (parent != null && !(clazz.isInstance(parent))) {
        parent = c instanceof JPopupMenu ? ((JPopupMenu) c).getInvoker() : c.getParent();
    }

    return (T) parent;
}

From source file:org.carewebframework.security.spring.controller.LoginWindowController.java

/**
 * If this authentication exception (or its cause) is of the expected type, return it.
 * Otherwise, return null.//from  w  ww.  j  ava2 s . c o m
 * 
 * @param exc The authentication exception.
 * @param clazz The desired type.
 * @return The original exception or its cause if one of them is of the expected type.
 */
@SuppressWarnings("unchecked")
protected static <T extends AuthenticationException> T getException(AuthenticationException exc,
        Class<T> clazz) {
    if (exc != null) {
        if (clazz.isInstance(exc)) {
            return (T) exc;
        } else if (clazz.isInstance(exc.getCause())) {
            return (T) exc.getCause();
        }
    }
    return null;
}

From source file:com.sonatype.security.ldap.api.DeepEqualsBuilder.java

private static Class getTestClass(Object lhs, Object rhs) {
    Class testClass = null;/*  w  w  w  .j  a v  a  2  s .  c  o m*/
    if (lhs != null && rhs != null) {

        Class lhsClass = lhs.getClass();
        Class rhsClass = rhs.getClass();

        if (lhsClass.isInstance(rhs)) {
            testClass = lhsClass;
            if (!rhsClass.isInstance(lhs)) {
                // rhsClass is a subclass of lhsClass
                testClass = rhsClass;
            }
        } else if (rhsClass.isInstance(lhs)) {
            testClass = rhsClass;
            if (!lhsClass.isInstance(rhs)) {
                // lhsClass is a subclass of rhsClass
                testClass = lhsClass;
            }
        }
    }
    return testClass;
}

From source file:energy.usef.core.util.XMLUtil.java

/**
 * Converts xml string to object and verifies if the the object is an instance of the specified class without validating.
 *
 * @param <T> message class/*from   ww  w. j  av  a 2  s.co  m*/
 *
 * @param xml xml string
 * @param clazz message object class
 *
 * @return corresponding object
 */
@SuppressWarnings("unchecked")
public static <T> T xmlToMessage(String xml, Class<T> clazz) {
    Object object = xmlToMessage(xml, false);
    if (object != null && clazz.isInstance(object)) {
        return (T) object;
    }

    throw new TechnicalException("Invalid XML content");
}

From source file:Main.java

/**
 * Change the type of array of Objects to an array of objects of type
 * newClass.//from   ww w .  j av a 2  s  . c  o m
 * 
 */
@SuppressWarnings("unchecked")
public static <T> T[] changeArrayType(Object[] array, Class<T> newClass) {

    ArrayList<T> newArray = new ArrayList<T>();

    for (int i = 0; i < array.length; i++) {
        // Only add those objects that can be cast to the new class
        if (newClass.isInstance(array[i])) {
            newArray.add(newClass.cast(array[i]));
        }
    }

    return newArray.toArray((T[]) Array.newInstance(newClass, 0));
}

From source file:com.discovery.darchrow.lang.ClassUtil.java

/**
 * ??./* w  w w  . j av a 2  s .  com*/
 * 
 * @param obj
 *            
 * @param klass
 *            
 * @return  obj  true
 * @see java.lang.Class#isInstance(Object)
 */
public static boolean isInstance(Object obj, Class<?> klass) {
    return klass.isInstance(obj);
}