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:org.archive.modules.fetcher.FetchHTTP.java

/**
 * @param curi//from  www.  ja v a  2 s.c  o  m
 *            CrawlURI that got a 401.
 * @param type
 *            Class of credential to get from curi.
 * @return Set of credentials attached to this curi.
 */
protected Set<Credential> getCredentials(CrawlURI curi, Class<?> type) {
    Set<Credential> result = null;

    if (curi.hasCredentials()) {
        for (Credential c : curi.getCredentials()) {
            if (type.isInstance(c)) {
                if (result == null) {
                    result = new HashSet<Credential>();
                }
                result.add(c);
            }
        }
    }
    return result;
}

From source file:org.jboss.spring.facade.KernelControllerListableBeanFactory.java

public String[] getBeanNamesForType(Class clazz, boolean includePrototypes, boolean allowEagerInit) {
    List<String> result = new ArrayList<String>();
    Set<ControllerContext> contexts = kernelController.getInstantiatedContexts(clazz);
    if (contexts != null && !contexts.isEmpty()) {
        for (ControllerContext context : contexts) {
            result.add(context.getName().toString());
        }/*from  w  w w .  j  a v a 2 s  . c  o  m*/
    }
    if (includePrototypes) {
        Set<ControllerContext> factories = kernelController.getInstantiatedContexts(AbstractBeanFactory.class);
        if (factories != null && !factories.isEmpty()) {
            for (ControllerContext kcc : factories) {
                Class<?> prototypeClass = getPrototypeClass(kcc);
                if (prototypeClass != null) {
                    if (clazz.isAssignableFrom(prototypeClass)) {
                        result.add(kcc.getName().toString());
                    }
                } else if (allowEagerInit) {
                    Object bean = createBean(kcc.getTarget());
                    if (clazz.isInstance(bean)) {
                        result.add(kcc.getName().toString());
                    }
                }
            }
        }
    }
    return result.toArray(new String[result.size()]);
}

From source file:org.opennms.netmgt.correlation.ncs.EventMappingRulesTest.java

private void testNodeEventMapping(Event event, Class<? extends ComponentEvent> componentEventClass,
        Set<String> componentIds) {
    // Get engine
    DroolsCorrelationEngine engine = findEngineByName("eventMappingRules");

    assertEquals("Expected nothing but got " + engine.getMemoryObjects(), 0, engine.getMemorySize());

    engine.correlate(event);/*w  w w  .j  a v  a  2  s.  com*/

    List<Object> memObjects = engine.getMemoryObjects();

    // expect an ComponentX event for each component
    assertEquals("Unexpected number of events added to memory " + memObjects, componentIds.size(),
            memObjects.size());

    Set<String> remainingIds = new HashSet<String>(componentIds);
    for (Object eventObj : memObjects) {

        assertTrue("expected " + eventObj + " to be an instance of " + componentEventClass,
                componentEventClass.isInstance(eventObj));
        assertTrue(eventObj instanceof ComponentEvent);

        ComponentEvent c = (ComponentEvent) eventObj;

        assertSame(event, c.getEvent());

        Component component = c.getComponent();

        String id = component.getForeignSource() + ":" + component.getForeignId();
        assertTrue("Expected an event for component " + id, remainingIds.remove(id));
    }
}

From source file:com.wabacus.config.component.other.ButtonsBean.java

public List<AbsButtonType> getDistinctCertainTypeButtonsList(Class buttonType) {
    if (mAllButtons == null || buttonType == null)
        return null;
    Iterator<String> itPositions = mAllButtons.keySet().iterator();
    List<AbsButtonType> lstButtonsResult = new ArrayList<AbsButtonType>();
    List<String> lstButtonNames = new ArrayList<String>();
    String position;//from  www .  ja va 2 s .  c  om
    while (itPositions.hasNext()) {
        position = itPositions.next();
        List<AbsButtonType> lstButtons = mAllButtons.get(position);
        if (lstButtons == null)
            continue;
        AbsButtonType buttonObj;
        for (int i = 0; i < lstButtons.size(); i++) {
            buttonObj = lstButtons.get(i);
            if (buttonObj == null)
                continue;
            if (buttonType.isInstance(buttonObj)) {
                if (lstButtonNames.contains(buttonObj.getName())) {
                    continue;
                }
                lstButtonNames.add(buttonObj.getName());
                lstButtonsResult.add(buttonObj);
            }
        }
    }
    return lstButtonsResult;
}

From source file:com.macrosoft.core.orm.hibernate.HibernateDao.java

/**
 * ,??// w w w.  j  a v  a2s  .c  om
 * 
 * @param father_id
 * @return
 */
public T getById(Object id) {
    T result = null;
    Class idClass = null;
    try {
        if (id != null) {
            // ??entity
            try {
                String idName = getIdName(entityClass);
                idClass = ReflectionUtils.getPropertyType(entityClass, idName);
            } catch (Exception e) {
                log.error(e, e);
            }
            if (idClass.isInstance(ZERO_STRING) == true) {
                String key = (String) id;
                if (StringUtils.isEmpty(key) == false) {
                    result = findUniqueBy("id", id);
                }
            } else {
                if (idClass.isInstance(ZERO_LONG) == true) {
                    if (((Long) id).longValue() > 0) {
                        result = findUniqueBy("id", id);
                    }
                } else {
                    if (idClass.isInstance(ZERO_INT) == true) {
                        if (((Integer) id).intValue() > 0) {
                            result = findUniqueBy("id", id);
                        }
                    } else {
                        result = findUniqueBy("id", id);
                    }
                }
            }
        }

    } catch (Exception ex) {
        log.error(ex, ex);
    }
    return result;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

@SuppressWarnings("unchecked")
private Map convertToTypedMap(Map original, String propertyName, Class requiredType,
        TypeDescriptor typeDescriptor) {

    if (!Map.class.isAssignableFrom(requiredType)) {
        return original;
    }//ww w.j  ava  2  s .  c  o m

    boolean approximable = CollectionFactory.isApproximableMapType(requiredType);
    if (!approximable && !canCreateCopy(requiredType)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Custom Map type [" + original.getClass().getName()
                    + "] does not allow for creating a copy - injecting original Map as-is");
        }
        return original;
    }

    boolean originalAllowed = requiredType.isInstance(original);
    typeDescriptor = typeDescriptor.narrow(original);
    TypeDescriptor keyType = typeDescriptor.getMapKeyTypeDescriptor();
    TypeDescriptor valueType = typeDescriptor.getMapValueTypeDescriptor();
    if (keyType == null && valueType == null && originalAllowed
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Iterator it;
    try {
        it = original.entrySet().iterator();
        if (it == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Map of type [" + original.getClass().getName()
                        + "] returned null Iterator - injecting original Map as-is");
            }
            return original;
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Map of type [" + original.getClass().getName()
                    + "] - injecting original Map as-is: " + ex);
        }
        return original;
    }

    Map convertedCopy;
    try {
        if (approximable) {
            convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
        } else {
            convertedCopy = (Map) requiredType.newInstance();
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot create copy of Map type [" + original.getClass().getName()
                    + "] - injecting original Map as-is: " + ex);
        }
        return original;
    }

    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
        String keyedPropertyName = buildKeyedPropertyName(propertyName, key);
        Object convertedKey = convertIfNecessary(keyedPropertyName, null, key,
                (keyType != null ? keyType.getType() : null), keyType);
        Object convertedValue = convertIfNecessary(keyedPropertyName, null, value,
                (valueType != null ? valueType.getType() : null), valueType);
        try {
            convertedCopy.put(convertedKey, convertedValue);
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Map type [" + original.getClass().getName()
                        + "] seems to be read-only - injecting original Map as-is: " + ex);
            }
            return original;
        }
        originalAllowed = originalAllowed && (key == convertedKey) && (value == convertedValue);
    }
    return (originalAllowed ? original : convertedCopy);
}

From source file:org.jboss.spring.facade.KernelControllerListableBeanFactory.java

public Map getBeansOfType(Class clazz, boolean includePrototypes, boolean allowEagerInit)
        throws BeansException {
    Map<String, Object> result = new HashMap<String, Object>();
    Set<ControllerContext> contexts = kernelController.getContexts(clazz, ControllerState.INSTALLED);
    for (ControllerContext context : contexts) {
        Object target = context.getTarget();
        result.put(context.getName().toString(), target);
    }/* w  ww  .j ava  2s.co  m*/
    if (includePrototypes) {
        Set<ControllerContext> factories = kernelController.getInstantiatedContexts(AbstractBeanFactory.class);
        if (factories != null && !factories.isEmpty()) {
            for (ControllerContext kcc : factories) {
                Class<?> prototypeClass = getPrototypeClass(kcc);
                if (prototypeClass != null) {
                    if (clazz.isAssignableFrom(prototypeClass)) {
                        result.put(kcc.getName().toString(), createBean(kcc.getTarget()));
                    }
                } else if (allowEagerInit) {
                    Object bean = createBean(kcc.getTarget());
                    if (clazz.isInstance(bean)) {
                        result.put(kcc.getName().toString(), bean);
                    }
                }
            }
        }
    }
    return result;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

@SuppressWarnings("unchecked")
private Collection convertToTypedCollection(Collection original, String propertyName, Class requiredType,
        TypeDescriptor typeDescriptor) {

    if (!Collection.class.isAssignableFrom(requiredType)) {
        return original;
    }/* www . j a  va 2 s  .  c  o m*/

    boolean approximable = CollectionFactory.isApproximableCollectionType(requiredType);
    if (!approximable && !canCreateCopy(requiredType)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Custom Collection type [" + original.getClass().getName()
                    + "] does not allow for creating a copy - injecting original Collection as-is");
        }
        return original;
    }

    boolean originalAllowed = requiredType.isInstance(original);
    typeDescriptor = typeDescriptor.narrow(original);
    TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
    if (elementType == null && originalAllowed
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Iterator it;
    try {
        it = original.iterator();
        if (it == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection of type [" + original.getClass().getName()
                        + "] returned null Iterator - injecting original Collection as-is");
            }
            return original;
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Collection of type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    Collection convertedCopy;
    try {
        if (approximable) {
            convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
        } else {
            convertedCopy = (Collection) requiredType.newInstance();
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot create copy of Collection type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    int i = 0;
    for (; it.hasNext(); i++) {
        Object element = it.next();
        String indexedPropertyName = buildIndexedPropertyName(propertyName, i);
        Object convertedElement = convertIfNecessary(indexedPropertyName, null, element,
                (elementType != null ? elementType.getType() : null), elementType);
        try {
            convertedCopy.add(convertedElement);
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection type [" + original.getClass().getName()
                        + "] seems to be read-only - injecting original Collection as-is: " + ex);
            }
            return original;
        }
        originalAllowed = originalAllowed && (element == convertedElement);
    }
    return (originalAllowed ? original : convertedCopy);
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *///from   ww w.j  a  v  a 2  s.  com
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = findTargetClass(key, classMap);
                    targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.warn("Property '" + key + "' has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class) {
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:com.jaliansystems.activeMQLite.impl.ObjectRepository.java

private boolean paramMatches(Method method, Object[] params) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (params != null && parameterTypes.length != params.length
            || params == null && parameterTypes.length != 0)
        return false;
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> class1 = parameterTypes[i];
        if (!class1.isPrimitive() && params[i] == null)
            continue;
        if (params[i] instanceof ObjectHandle) {
            params[i] = getObject(((ObjectHandle) params[i]));
        }//from   w w w .j av  a 2  s .  co  m
        if (class1.isPrimitive()) {
            if (params[i] instanceof Boolean && class1 != Boolean.TYPE)
                return false;
            if (params[i] instanceof Integer && class1 != Integer.TYPE)
                return false;
            if (params[i] instanceof Long && class1 != Long.TYPE)
                return false;
            if (params[i] instanceof Short && class1 != Short.TYPE)
                return false;
            if (params[i] instanceof Float && class1 != Float.TYPE)
                return false;
            if (params[i] instanceof Double && class1 != Double.TYPE)
                return false;
            if (params[i] instanceof Byte && class1 != Byte.TYPE)
                return false;
        } else if (!class1.isInstance(params[i]))
            return false;
    }
    return true;
}