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:com.architexa.store.StoreUtil.java

@SuppressWarnings("unchecked")
public static <T extends Object> void loadEclipseClasses(List<T> loadedClasses, Class<?> loadType,
        String extPt) {//from w  w  w .ja v a  2s  . c om
    List<Object> untypedLoadedClasses = new ArrayList<Object>(10);
    loadEclipseClasses(untypedLoadedClasses, extPt);
    for (Object untypedLoadedClass : untypedLoadedClasses) {
        if (loadType.isInstance(untypedLoadedClass))
            loadedClasses.add((T) untypedLoadedClass);
        else
            logger.error("Expecting type: " + loadType + " got: " + untypedLoadedClass.getClass(),
                    new Exception());
    }
}

From source file:com.adobe.acs.commons.util.TypeUtil.java

/**
 * Converts a JSONObject to a simple Map. This will only work properly for
 * JSONObjects of depth 1./*w  ww .  j a v  a2 s .  com*/
 * <p/>
 * Resulting map will be type'd <String, T> where T is the type of the second parameter (klass)
 *
 * @param json
 * @param klass
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Map<String, T> toMap(JSONObject json, Class<T> klass) throws JSONException {
    final HashMap<String, T> map = new HashMap<String, T>();
    final List<?> keys = IteratorUtils.toList(json.keys());

    for (final Object key : keys) {
        final String strKey = key.toString();
        final Object obj = json.get(strKey);
        if (klass.isInstance(obj)) {
            // Only add objects of this type
            map.put(strKey, (T) obj);
        }
    }

    return map;
}

From source file:io.fabric8.kubernetes.api.ParseTest.java

public static <T> T assertParseExampleFile(String fileName, Class<T> clazz) throws Exception {
    File exampleFile = new File(getKubernetesExamplesDir(), fileName);
    assertFileExists(exampleFile);//from ww w  .j  ava 2s.c  o m
    Object answer = OBJECT_MAPPER.readerFor(clazz).readValue(exampleFile);
    assertNotNull("Null returned while unmarshalling " + exampleFile, answer);
    LOG.info("Parsed: " + fileName + " as: " + answer);
    assertTrue("Is not an instance of " + clazz.getSimpleName() + " was: " + answer.getClass().getName(),
            clazz.isInstance(answer));
    return clazz.cast(answer);
}

From source file:com.ctriposs.r2.transport.http.client.HttpClientFactory.java

private static <T> T coerce(String key, Object value, Class<T> valueClass) {
    if (value == null) {
        return null;
    }/*from ww w . ja  va 2s. c  om*/
    if (!valueClass.isInstance(value)) {
        throw new IllegalArgumentException("Property " + key + " is of type " + value.getClass().getName()
                + " but must be " + valueClass.getName());
    }
    return valueClass.cast(value);
}

From source file:de.cosmocode.collections.utility.Convert.java

private static <E extends Enum<E>> E doIntoEnum(Object value, Class<E> enumType) {
    Preconditions.checkNotNull(enumType, "EnumType");
    if (enumType.isInstance(value))
        return enumType.cast(value);
    final Long ordinal = doIntoLong(value);
    if (ordinal == null) {
        final String name = doIntoString(value);
        if (name == null)
            return null;
        try {// www.j  ava 2s.  c o  m
            return Enum.valueOf(enumType, name.toUpperCase());
        } catch (IllegalArgumentException e) {
            return null;
        }
    } else {
        try {
            return Enums.valueOf(enumType, ordinal.intValue());
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }
}

From source file:com.twitter.distributedlog.DLMTestUtil.java

public static <T> void validateFutureFailed(Future<T> future, Class exClass) {
    try {/*from   ww w  .j a  v a 2s  .co  m*/
        Await.result(future);
    } catch (Exception ex) {
        LOG.info("Expected: {} Actual: {}", exClass.getName(), ex.getClass().getName());
        assertTrue("exceptions types equal", exClass.isInstance(ex));
    }
}

From source file:com.google.dart.engine.internal.index.AbstractDartTest.java

/**
 * @return {@link ASTNode} which has required offset and type.
 *//*from  w  w  w  .  jav  a2s .  c  o  m*/
public static <E extends ASTNode> E findNode(ASTNode root, final int offset, final Class<E> clazz) {
    final AtomicReference<E> resultRef = new AtomicReference<E>();
    root.accept(new GeneralizingASTVisitor<Void>() {
        @Override
        @SuppressWarnings("unchecked")
        public Void visitNode(ASTNode node) {
            if (node.getOffset() <= offset && offset < node.getEnd() && clazz.isInstance(node)) {
                resultRef.set((E) node);
            }
            return super.visitNode(node);
        }
    });
    E result = resultRef.get();
    assertNotNull(result);
    return result;
}

From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java

public static <T> T getConfiguration(File configurationFile, Class<? extends T> configurationClass)
        throws Exception {
    if (configurationClass == null) {
        return null;
    }//from w  w  w . j  av  a2 s  .  c om
    ConfigurationCacheEntry entry = configurationCache.getIfPresent(configurationFile);
    if (entry == null || !configurationClass.isInstance(entry.object) || entry.error) {
        if (entry != null && entry.error) {
            logger.warn("Cached configuration for {} is in error state, forcing a reload",
                    configurationFile.getAbsolutePath());
        } else if (entry != null && !configurationClass.isInstance(entry.object)) {
            logger.warn("Cached configuration for {} is an instance of the wrong class, forcing a reload",
                    configurationFile.getAbsolutePath());
        }
        T configuration = loadConfiguration(configurationFile, configurationClass);
        entry = new ConfigurationCacheEntry(configuration, configurationClass, configurationFile.lastModified(),
                false);
        configurationCache.put(configurationFile, entry);
    }
    return (T) entry.object;
}

From source file:RssAtomGenerationTest.java

public static <T> T convertObject(final T destination, final Object source, FeedType type, Object... context) {
    Map<Class, Object> contentMap = new HashMap<Class, Object>();
    for (Object o : context) {
        contentMap.put(o.getClass(), o);
    }/*from ww  w .  j  a va2s.  c  o m*/
    final Method[] methods = source.getClass().getMethods();
    for (Method method : methods) {
        final boolean refPresent = method.isAnnotationPresent(SyndicationRefs.class);
        if (refPresent || (method.isAnnotationPresent(SyndicationElement.class)
                && method.getAnnotation(SyndicationElement.class).type().equals(type))) {
            SyndicationElement annotation = null;
            if (refPresent) {
                final SyndicationElement[] value = method.getAnnotation(SyndicationRefs.class).value();
                for (SyndicationElement element : value) {
                    if (element.type().equals(type)) {
                        annotation = element;
                        break;
                    }
                }
                if (annotation == null) {
                    continue;
                }
            } else {
                annotation = method.getAnnotation(SyndicationElement.class);
            }
            //final SyndicationElement annotation =
            final String name = annotation.name();
            try {
                final Object initValue = method.invoke(source);
                Object value = null;
                if (!(annotation.converter().isAssignableFrom(NoopConverter.class))) {
                    final Converter converter = annotation.converter().newInstance();
                    value = converter.convert(initValue);
                }
                if (!(annotation.transformer().isAssignableFrom(NoopTransformer.class))) {
                    contentMap.put(initValue.getClass(), initValue);
                    final Class<?> transformer = annotation.transformer();
                    final Method[] transformerMethods = transformer.getMethods();
                    for (Method transformerMethod : transformerMethods) {
                        if (transformerMethod.isAnnotationPresent(ContextTransformable.class)) {
                            final Class<?>[] parameterTypes = transformerMethod.getParameterTypes();
                            List<Object> parameters = new ArrayList<Object>();
                            for (Class clazz : parameterTypes) {
                                if (contentMap.containsKey(clazz)) {
                                    parameters.add(contentMap.get(clazz));
                                } else {
                                    boolean found = false;
                                    for (Object obj : contentMap.values()) {
                                        if (clazz.isInstance(obj)) {
                                            parameters.add(obj);
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (!found) {
                                        parameters.add(null);
                                    }
                                }
                            }
                            if (Modifier.isStatic(transformerMethod.getModifiers())) {
                                value = transformerMethod.invoke(null, parameters.toArray());
                            } else {
                                value = transformerMethod.invoke(transformer.newInstance(),
                                        parameters.toArray());
                            }
                            break;
                        }
                    }

                }
                BeanUtils.setProperty(destination, name, value);
            } catch (Exception e) {
                log.error("test", e);
                e.printStackTrace();
            }

        }
    }
    return destination;
}

From source file:de.xwic.appkit.core.util.CollectionUtil.java

/**
 * @param collection/*from  w w w.j  a  v  a 2 s.  c  o  m*/
 * @param resultClass
 * @return
 */
public static boolean isOf(final Collection<?> collection, final Class<?> resultClass) {
    Validate.notNull(resultClass, "No result class provided.");
    Validate.notNull(collection, "No collection provided.");
    if (collection.isEmpty()) {
        return true;
    }
    for (final Object cal : collection) {
        if (cal != null && !resultClass.isInstance(cal)) {
            return false;
        }
    }
    return true;
}