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:it.cnr.icar.eric.common.BindingUtility.java

/**
 * Gets the Set of ReferenceInfo for specified reference attribute within RegistryObject.
 *
 * Reference attributes based on scanning rim.xsd for anyURI.
 *
 * @param ro specifies the RegistryObject whose reference attribute is being sought.
 *
 * @param idMap The HashMap with old temporary id to new permanent id mapping.
 *
 *///from ww w.j a  v  a2  s .co m
private void processRefAttribute(RegistryObjectType ro, String className, Set<ReferenceInfo> refInfos,
        Map<?, ?> idMap, String attribute) throws JAXRException {
    try {
        //Use reflections API to get the attribute value, check if it needs to be mapped
        //and set it with mapped value if needed and add the final value to refInfos
        Class<?> clazz = Class.forName(className);
        if (!(clazz.isInstance(ro))) {
            return;
        }

        //Get the attribute value by calling get method
        String getMethodName = "get" + attribute;
        Method getMethod = clazz.getMethod(getMethodName, (java.lang.Class[]) null);

        //Invoke getMethod to get the reference target object's id
        String targetObjectId = (String) getMethod.invoke(ro, (java.lang.Object[]) null);

        if (targetObjectId != null) {
            //Check if id has been mapped to a new id
            if (idMap.containsKey(targetObjectId)) {
                //Replace old id with new id
                targetObjectId = (String) idMap.get(targetObjectId);

                //Use set method to set new value on ro
                @SuppressWarnings("rawtypes")
                Class[] parameterTypes = new Class[1];
                Object[] parameterValues = new Object[1];
                parameterTypes[0] = Class.forName("java.lang.String");
                parameterValues[0] = targetObjectId;
                String setMethodName = "set" + attribute;
                Method setMethod = clazz.getMethod(setMethodName, parameterTypes);
                setMethod.invoke(ro, parameterValues);
            }

            ReferenceInfo refInfo = new ReferenceInfo(ro.getId(), targetObjectId, attribute);
            refInfos.add(refInfo);
        }

    } catch (Exception e) {
        //throw new OMARExeption("Class = " ro.getClass() + " attribute = " + attribute", e);
        log.error(CommonResourceBundle.getInstance().getString("message.ErrorClassAttribute",
                new Object[] { ro.getClass(), attribute }));
        e.printStackTrace();
    }

}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

/**
 * This will prevent unchecked warnings and will also validate the content properly.
 *
 * @param iface the expected type of the elements.
 * @param obj the input Object, ideally a Set of the given type
 * @return the input as a Set of the given type.
 *//*from   www  .jav a2s .c o  m*/
private static <T> Set<T> transformToSet(Class<T> iface, Object obj) {
    final Logger logger = LoggerFactory.getLogger(ApplicationPreferences.class);

    Set<T> resultSet = null;
    if (obj instanceof Set) {
        Set set = (Set) obj;
        resultSet = new HashSet<>(set.size());
        for (Object current : set) {
            if (iface.isInstance(current)) {
                resultSet.add(iface.cast(current));
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Expected {} but got {}!", iface.getName(), current);
            }
        }
    } else {
        if (logger.isWarnEnabled())
            logger.warn("Expected Set but got {}!", obj);
    }
    return resultSet;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

/**
 * This will prevent unchecked warnings and will also validate the content properly.
 *
 * @param iface the expected type of the elements.
 * @param obj the input Object, ideally a List of the given type
 * @return the input as a List of the given type.
 *//*from w ww .  ja  v  a  2s. c om*/
private static <T> List<T> transformToList(Class<T> iface, Object obj) {
    final Logger logger = LoggerFactory.getLogger(ApplicationPreferences.class);

    List<T> resultList = null;
    if (obj instanceof List) {
        List list = (List) obj;
        resultList = new ArrayList<>(list.size());
        for (Object current : list) {
            if (iface.isInstance(current)) {
                resultList.add(iface.cast(current));
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Expected {} but got {}!", iface.getName(), current);
            }
        }
    } else {
        if (logger.isWarnEnabled())
            logger.warn("Expected List but got {}!", obj);
    }
    return resultList;
}

From source file:fr.cls.atoll.motu.library.misc.data.CatalogData.java

/**
 * Searches objects from a jaxbElement object list according to a specific class .
 * /*from   ww w .  j a v  a  2  s.  c om*/
 * @param listObject list in which one searches
 * @param classObject class to search
 * 
 * @return a list that contains object corresponding to classObject parameter (can be empty)
 */
static public List<Object> findJaxbElement(List<Object> listObject, Class<?> classObject) {

    if (listObject == null) {
        return null;
    }

    List<Object> listObjectFound = new ArrayList<Object>();

    for (Object elt : listObject) {
        if (elt == null) {
            continue;
        }

        if (classObject.isInstance(elt)) {
            listObjectFound.add(elt);
        }

        if (!(elt instanceof JAXBElement)) {
            continue;
        }

        JAXBElement<?> jabxElement = (JAXBElement<?>) elt;

        // System.out.println(jabxElement.getClass().getName());
        // System.out.println(jabxElement.getDeclaredType().getName());

        Object objectElt = jabxElement.getValue();

        if (classObject.isInstance(objectElt)) {
            listObjectFound.add(objectElt);
        }
    }

    return listObjectFound;

}

From source file:com.gs.collections.impl.test.Verify.java

/**
 * Assert that the given object is an instanceof expectedClassType.
 *//*from   w w w.j  a  v  a  2 s.c om*/
public static void assertInstanceOf(String objectName, Class<?> expectedClassType, Object actualObject) {
    try {
        if (!expectedClassType.isInstance(actualObject)) {
            Assert.fail(objectName + " is not an instance of " + expectedClassType.getName());
        }
    } catch (AssertionError e) {
        Verify.throwMangledException(e);
    }
}

From source file:com.cloudbees.hudson.plugins.folder.AbstractFolder.java

/**
 * Removes any actions of the specified type.
 * Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
 * Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}
 *
 * @param clazz the type of actions to remove
 * @return {@code true} if this actions changed as a result of the call
 * @since FIXME//from   w ww . java 2 s.  co  m
 */
// TODO remove once baseline has JENKINS-39404
@SuppressWarnings({ "ConstantConditions", "deprecation" })
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public boolean removeActions(@Nonnull Class<? extends Action> clazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("Action type must be non-null");
    }
    // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
    List<Action> old = new ArrayList<Action>();
    List<Action> current = super.getActions();
    for (Action a : current) {
        if (clazz.isInstance(a)) {
            old.add(a);
        }
    }
    return current.removeAll(old);
}

From source file:org.apache.river.springframework.config.ApplicationContextAdapter.java

@Override
public Object getEntry(String component, String name, Class type, Object defaultValue, Object data)
        throws ConfigurationException {
    Objects.requireNonNull(name, "The name parameter must not be null.");
    Objects.requireNonNull(name, "The type parameter must not be null.");

    Object value = null;/*w  w  w  . jav  a2 s .c  o m*/

    try {
        if (component != null && !component.isEmpty()) {
            try {
                value = adaptee.getBean(component + "." + name);
            } catch (NoSuchBeanDefinitionException e) {
            }
        }
        if (value == null) {
            try {
                value = adaptee.getBean(name);
            } catch (NoSuchBeanDefinitionException e) {
            }
        }
    } catch (BeansException e) {
        throw new ConfigurationException("Unable to get configuration value.", e);
    }

    if (value == null) {
        if (defaultValue == Configuration.NO_DEFAULT) {
            throw new NoSuchEntryException("No configuration value found.");
        } else {
            value = defaultValue;
        }
    }

    if (value != null) {
        if ((type.isPrimitive() && (type == boolean.class && value instanceof Boolean)
                || (type == char.class && value instanceof Character)
                || (type == byte.class && value instanceof Byte)
                || (type == short.class && value instanceof Short)
                || (type == int.class && value instanceof Integer)
                || (type == long.class && value instanceof Long)
                || (type == float.class && value instanceof Float)
                || (type == double.class && value instanceof Double)) || type.isInstance(value)) {

        } else {
            throw new IllegalArgumentException("Configuration value cannot be converted to type.");
        }
    }

    return value;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse the next value as an object. If the next value is {@link JsonToken#NULL}, returns
 * null.//from  w w  w. j ava2s  . c om
 * <p/>
 * This method will use the provide parser, or if none is provided, will attempt find an
 * appropriate parser based on the discrimination value found in the next object. If none is
 * found, then this method returns a {@link JSONObject}.
 *
 * @param reader The JsonReader to use. Calls to {@link JsonReader#beginObject()} and {@link
 * JsonReader#endObject()} will be taken care of by this method.
 * @param parser The parser to use, or null if this method should find an appropriate one on its
 * own.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 * @param expectedType The expected class of the resulting object. If the result is not an
 * instance of this class, an exception is thrown.
 *
 * @throws IllegalStateException if the resulting object is not an instance of {@code
 * expectedType}.
 */
public static Object parseJsonObject(JsonReader reader, JsonObjectParser<?> parser, String key,
        Class<?> expectedType) throws IOException, IllegalStateException {
    if (handleNull(reader)) {
        return null;
    }
    assertType(reader, key, JsonToken.BEGIN_OBJECT);

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();
    String discriminationValue = null;
    Object result = null;
    reader.beginObject();
    if (parser != null) {
        result = parser.parseJsonObject(null, reader, discriminationName, null);
    } else if (reader.hasNext()) {
        String firstName = reader.nextName();
        final String discriminationKeyName = ContextHolder.getContext().getSettings().getDiscriminationName();
        if (discriminationKeyName.equals(firstName)) {
            discriminationValue = reader.nextString();
            parser = ContextHolder.getContext().getJsonObjectParserTable().get(discriminationValue);
            if (parser != null) {
                result = parser.parseJsonObject(null, reader, discriminationName, discriminationValue);
            } else {
                result = parseSpecificJsonObjectDelayed(reader, discriminationKeyName, discriminationValue);
            }
        } else {
            result = parseSpecificJsonObjectDelayed(reader, firstName, null);
        }

    }
    reader.endObject();

    if (result == null) {
        result = new JSONObject();
    }

    JsonObjectParser<?> unknownObjectParser = ContextHolder.getContext().getSettings().getUnknownObjectParser();
    if (result instanceof JSONObject && unknownObjectParser != null) {
        result = unknownObjectParser.parseJsonObject((JSONObject) result, null, discriminationName,
                discriminationValue);
    }

    if (expectedType != null && !(expectedType.isInstance(result))) {
        throw new IllegalStateException(
                String.format(Locale.US, "Could not convert value at \"%s\" to %s from %s.", key,
                        expectedType.getCanonicalName(), result.getClass().getCanonicalName()));
    }
    return result;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

/**
 * This will prevent unchecked warnings and will also validate the content properly.
 *
 * @param keyClass the expected type of the keys.
 * @param valueClass the expected type of the values.
 * @param obj the input Object, ideally a Map of the given types
 * @return the input as a Map of the given types.
 *//*from ww w  .  j  ava  2s  .  co m*/
private static <K, V> Map<K, V> transformToMap(Class<K> keyClass, Class<V> valueClass, Object obj) {
    final Logger logger = LoggerFactory.getLogger(ApplicationPreferences.class);

    Map<K, V> resultMap = null;
    if (obj instanceof Map) {
        Map map = (Map) obj;
        resultMap = new HashMap<>(map.size());
        for (Object c : map.entrySet()) {
            Map.Entry current = (Map.Entry) c;
            Object key = current.getKey();
            Object value = current.getValue();

            if (!keyClass.isInstance(key)) {
                if (logger.isWarnEnabled())
                    logger.warn("Expected {} as key but got {}!", keyClass.getName(), key);
                continue;
            }
            if (!valueClass.isInstance(value)) {
                if (logger.isWarnEnabled())
                    logger.warn("Expected {} as value but got {}!", valueClass.getName(), value);
                continue;
            }
            resultMap.put(keyClass.cast(key), valueClass.cast(value));
        }
    } else {
        if (logger.isWarnEnabled())
            logger.warn("Expected Map but got {}!", obj);
    }
    return resultMap;
}