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

/**
 * Same as above, but implemented via a new array list instead of a cast.
 * @param T         the target type/*w ww .  ja  v  a 2 s . c  om*/
 * @param l         the input collection
 * @param tClass    T's class
 * @return a new array list with all items of l cast into T
 * 
 * @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(Collection<?> l, Class<T> tClass) {
    if (l == null)
        return null;

    ArrayList<T> res = new ArrayList<T>();
    for (Object o : l)
        if (o != null && !tClass.isInstance(o))
            throw new ClassCastException("ClassCast from " + o.getClass() + " to " + tClass);
        else
            res.add((T) o);
    return res;
}

From source file:edu.byu.nlp.util.asserts.MoreAsserts.java

public static void assertFails(Runnable runnable, Class<? extends Exception> expectedException) {
    try {/*w  w w. j  a v a2  s . com*/
        runnable.run();
    } catch (Exception e) {

        if (!expectedException.isInstance(e)) {
            Fail.fail("Threw the wrong kind of exception: " + e.getClass().getName()
                    + " instead of the expected " + expectedException.getName(), e);
        }

        return; // good failure
    }

    Fail.fail("should have thrown a " + expectedException.getName() + " exception but did not!");

}

From source file:Main.java

public static Collection asTargetTypeCollection(Collection c, Class targetCollectionClass) {
    if (targetCollectionClass == null)
        throw new IllegalArgumentException("'targetCollectionClass' must be not null");
    if (c == null)
        return null;
    if (targetCollectionClass.isInstance(c))
        return c;

    Collection result = null;/* w  w w.j  a v  a  2 s. c  o  m*/

    try {
        result = (Collection) targetCollectionClass.newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "targetCollectionClass=" + targetCollectionClass.getName() + " is not correct!", e);
    }

    result.addAll(c);
    return result;
}

From source file:Main.java

/**
 * provides a view to the given collection, that only contains objects that are instances of the given clazz. It
 * uses the guava-methods {@link Collections2#filter(Collection, Predicate)} and
 * {@link Collections2#transform(Collection, Function)}.
 * //from  w w  w . j  a  va 2 s.  co m
 * The returned collection is immutable.
 */
public static <TargetType> Collection<TargetType> filterCollectionByClass(Collection<?> source,
        final Class<TargetType> clazz) {
    Collection<?> filtered = Collections2.filter(source, new Predicate<Object>() {
        @Override
        public boolean apply(Object input) {
            return clazz.isInstance(input);
        }
    });
    return Collections2.transform(filtered, new Function<Object, TargetType>() {
        @SuppressWarnings("unchecked")
        @Override
        public TargetType apply(Object input) {
            return (TargetType) input;
        }
    });
}

From source file:info.archinnov.achilles.internal.validation.Validator.java

public static <T> void validateInstanceOf(Object entity, Class<T> targetClass, String message, Object... args) {
    validateNotNull(entity, "Entity '%s' should not be null", entity);
    if (!targetClass.isInstance(entity)) {
        throw new AchillesException(format(message, args));
    }//from  w ww.j av  a2s  . c  om
}

From source file:Main.java

static Unsafe getSMU() {
    try {/*from   w w w  .  ja v a 2 s  .co  m*/
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException tryReflectionInstead) {
        // ignore
    }
    try {
        return java.security.AccessController.doPrivileged((PrivilegedExceptionAction<Unsafe>) () -> {
            Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
            for (Field f : k.getDeclaredFields()) {
                f.setAccessible(true);
                Object x = f.get(null);
                if (k.isInstance(x))
                    return k.cast(x);
            }
            throw new NoSuchFieldError("the Unsafe");
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}

From source file:Main.java

/**
 * Typecheck as above, performing on map values
 * @param <K>    Key type/*from  www. j  a  v  a 2s  . co m*/
 * @param <V>    Designated value type
 * @param m      the map to check
 * @param vClass the value type's class
 * @return m, accordingly cast, if no classCastException is thrown
 * 
 * @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 <K, V> Map<K, V> typecheck(Map<K, ?> m, Class<V> vClass) {
    if (m == null)
        return null;
    for (Map.Entry<K, ?> e : m.entrySet()) {
        Object o = e.getValue();
        if (o != null && !vClass.isInstance(o))
            throw new ClassCastException("ClassCast from " + o.getClass() + " to " + vClass);
    }
    return (Map<K, V>) m;
}

From source file:com.mewin.util.Utils.java

public static Plugin getPlugin(String plugName, Class pluginClass) {
    Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(plugName);

    if (plugin != null || !pluginClass.isInstance(plugin)) {
        return null;
    }//from w ww  . j  av a2 s . c om

    return plugin;
}

From source file:eu.eidas.auth.engine.metadata.MetadataUtil.java

@Nullable
private static <T extends RoleDescriptor> T getFirstRoleDescriptor(@Nonnull EntityDescriptor entityDescriptor,
        @Nonnull Class<T> clazz) {
    for (RoleDescriptor rd : entityDescriptor.getRoleDescriptors()) {
        if (clazz.isInstance(rd)) {
            return (T) rd;
        }/*  w ww  .  ja  v  a  2 s.c o  m*/
    }
    return null;
}

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.
 *
 * @param <T> message class/*from   w w  w.j  av a2s  . com*/
 *
 * @param xml xml string
 * @param clazz message object class
 * @param validate true when the xml needs to be validated
 *
 * @return corresponding object
 */
@SuppressWarnings("unchecked")
public static <T> T xmlToMessage(String xml, Class<T> clazz, boolean validate) {
    Object object = xmlToMessage(xml, validate);
    if (object != null && clazz.isInstance(object)) {
        return (T) object;
    }

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