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

@SuppressWarnings("unchecked")
public static <O> List<O> convert(List<?> list, Class<O> clazz) {
    if (list == null) {
        return null;
    }/*from w w  w.  ja v a  2s  .  c  om*/

    List<O> converted = new ArrayList<O>();

    for (Object item : list) {
        if (clazz.isInstance(item)) {
            converted.add((O) item);
        }
    }

    return converted;
}

From source file:com.jadarstudios.rankcapes.bukkit.CapePackValidator.java

/**
 * Validates an Animated cape node./* www . jav a  2s.  c om*/
 *
 * @param node the node thought to be an Animated cape node
 *
 * @throws InvalidCapePackException thrown if the node is invalid.
 */
public static void validateAnimatedCapeNode(Map node) throws InvalidCapePackException {
    for (Map.Entry<String, Class<?>> possibleField : ANIMATED_FIELDS.entrySet()) {
        Object jsonField = node.get(possibleField.getKey());
        Class field = possibleField.getValue();
        if (jsonField != null && !field.isInstance(jsonField)) {
            throw new InvalidCapePackException(
                    String.format("The value \"%s\" is not valid for key \"%s\" which requires a \"%s\" value",
                            jsonField, possibleField.getKey(), field.getSimpleName()));
        }
    }
}

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

/**
 * This method helps palliating the absence of multi-catch (introduced in Java 7) - catch the lower common
 * denominator exception and let this method do the rest - <strong>Use with great care!</strong>.
 * <strong>Warning:</strong> this method can be abused, and would let one throw undeclared exceptions, which would
 * in turn produce unexpected and undesirable effects on calling code. Just resist the urge to use this outside
 * "multi-catch" scenarios./*  w  ww  . ja va  2s. c o  m*/
 */
@SuppressWarnings("unchecked")
public static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions) {
    if (RuntimeException.class.isInstance(e)) {
        throw (RuntimeException) e;
    }
    for (Class<? extends Throwable> allowedException : allowedExceptions) {
        if (allowedException.isInstance(e)) {
            sneakyThrow(e);
        }
    }
    throw new Error("Caught the following exception, which was not allowed: ", e);
}

From source file:Main.java

/**
 * Check the type of list contents (for the situations where a simple upcast
 * is not enough.) As Java generics are implemented via erasure,
 * unfortunately the target class has to be passed as a parameter.
 * <p>//  w  w w  .j  a va 2 s.  co  m
 * Basically, you can convert a list to a typed list via this method, using:
 * <pre>
 *   List someList = ...; // from somewhere else
 *   List&lt;MyType&gt; = typecheck(someList, MyType.class);
 * </pre>
 * The method will raise a class cast exception, if the input list contains
 * any element, that is not instanceof MyType or null.
 * @param T      the target type
 * @param l      the input list
 * @param tClass T's class
 * @return l as a parameterized type
 * 
 * @deprecated In the most common use case this is unnecessary. In the second
 *       common use case this is a sign that you have not understood generics.
 */
public static <T> List<T> typecheck(List<?> l, Class<T> tClass) {
    if (l == null)
        return null;

    for (Object o : l)
        if (o != null && !tClass.isInstance(o))
            throw new ClassCastException("ClassCast from " + o.getClass() + " to " + tClass);

    return (List<T>) l;
}

From source file:com.crossbusiness.resiliency.aspect.AbstractRetryAspect.java

static boolean isRetryableException(Throwable ex, Class<? extends Exception>[] retryableExceptions) {
    boolean isRetryableException = false;
    for (Class<? extends Exception> exception : retryableExceptions) {
        if (exception.isInstance(ex)) {
            isRetryableException = true;
            break;
        }/*from w ww  .j  av a2  s .  c o  m*/
    }
    return isRetryableException;
}

From source file:Main.java

public static List<JComponent> getComponents(Container owner, Class<?> clazz, boolean onlyVisible) {
    List<JComponent> list = new ArrayList<JComponent>();
    for (Component c : owner.getComponents()) {
        if (clazz.isInstance(c) && (!onlyVisible || c.isShowing()))
            list.add((JComponent) c);
        else if (c instanceof JComponent) {
            for (JComponent b : getComponents((JComponent) c, clazz, onlyVisible))
                list.add(b);/*from w  w w .j a  va  2 s .co m*/
        }
    }
    return list;
}

From source file:me.bulat.jivr.webmin.utils.EntityUtils.java

/**
 * Look up the entity of the given class with the given id in the given collection.
 *
 * @param entities    the collection to search
 * @param entityClass the entity class to look up
 * @param entityId    the entity id to look up
 * @return the found entity/*w ww.j a  va  2s .c  om*/
 * @throws ObjectRetrievalFailureException if the entity was not found
 */
public static <T extends BaseEntity> T getById(Collection<T> entities, Class<T> entityClass, int entityId)
        throws ObjectRetrievalFailureException {
    for (T entity : entities) {
        if (entity.getId() == entityId && entityClass.isInstance(entity)) {
            return entity;
        }
    }
    throw new ObjectRetrievalFailureException(entityClass, entityId);
}

From source file:Main.java

/**
 * Given an object that is presumably a JAXBElement<clazz>, return object.getValue(). This method
 * is useful for parsing XML elements of type xs:any (but where you know the type is clazz).
 * //from   w  w  w .j a  v  a 2  s.c  o m
 * If object is not a JAXBElement<clazz>, return null else return
 * ((JAXBElement<?>)object).getValue()
 * 
 * @param jaxbElement
 * @param clazz
 * @return
 */
public static Object unwrap(Object jaxbElement, Class<?> clazz) {
    if (jaxbElement instanceof JAXBElement<?>) {
        Object ret = ((JAXBElement<?>) jaxbElement).getValue();
        if (clazz.isInstance(ret)) {
            return ret;
        } else {
            System.err.println("Cannot cast " + ret + " to class " + clazz + " (actual class is " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    + ret.getClass() + ")."); //$NON-NLS-1$
            return null; // TODO(enr): Throw an exception here
        }
    } else if (clazz.isInstance(jaxbElement)) {
        return jaxbElement;
    } else {
        System.err.println("Cannot cast " + jaxbElement + " to class JAXBElement<?> or " + clazz //$NON-NLS-1$ //$NON-NLS-2$
                + " (actual class is " + jaxbElement.getClass() + ")."); //$NON-NLS-1$ //$NON-NLS-2$
        return null; // TODO(enr): Throw an exception here
    }
}

From source file:Main.java

/**
 * Find a single value of the given type in the given Collection.
 * @param collection the Collection to search
 * @param type the type to look for//www . ja v a 2 s.co  m
 * @return a value of the given type found if there is a clear match,
 * or {@code null} if none or more than one such value found
 */
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
    if (isEmpty(collection))
        return null;
    T value = null;
    for (Object element : collection) {
        if (type == null || type.isInstance(element)) {
            if (value != null) {
                // More than one value found... no clear single value.
                return null;
            }
            value = (T) element;
        }
    }
    return value;
}

From source file:com.branded.holdings.qpc.util.EntityUtils.java

/**
 * Look up the entity of the given class with the given id in the given collection.
 *
 * @param entities    the collection to search
 * @param entityClass the entity class to look up
 * @param entityId    the entity id to look up
 * @return the found entity/*ww  w . j a  va 2 s .  c o  m*/
 * @throws ObjectRetrievalFailureException
 *          if the entity was not found
 */
public static <T extends BaseEntity> T getById(Collection<T> entities, Class<T> entityClass, int entityId)
        throws ObjectRetrievalFailureException {
    for (T entity : entities) {
        if (entity.getId().intValue() == entityId && entityClass.isInstance(entity)) {
            return entity;
        }
    }
    throw new ObjectRetrievalFailureException(entityClass, entityId);
}