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:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java

/**
 * Configure an object. If the object is of the approprate class, the XML configuration script
 * is applied to the object.//from   www. j a  v a 2s. c  om
 * 
 * @param obj The object to be configured.
 * @exception ClassNotFoundException
 * @exception NoSuchMethodException
 * @exception InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void configure(Object obj) throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, InstantiationException, IllegalAccessException {
    //Check the class of the object
    Class oClass = nodeClass(_config);
    if (oClass != null) {
        if (obj != null && !oClass.isInstance(obj))
            throw new IllegalArgumentException("Object is not of type " + oClass);
        if (obj == null)
            obj = oClass.newInstance();
    }
    configure(obj, _config, 0);
}

From source file:com.google.code.ssm.spring.SSMCache.java

/**
 * Required by Spring 4.0//from w ww.  jav a 2  s .c o  m
 * 
 * @since 3.4.0
 */
@SuppressWarnings("unchecked")
public <T> T get(Object key, Class<T> type) {
    if (!cache.isEnabled()) {
        LOGGER.warn("Cache {} is disabled. Cannot get {} from cache", cache.getName(), key);
        return null;
    }

    Object value = getValue(key);
    if (value == null) {
        LOGGER.info("Cache miss. Get by key {} and type {} from cache {}",
                new Object[] { key, type, cache.getName() });
        return null;
    }

    if (value instanceof PertinentNegativeNull) {
        return null;
    }

    if (type != null && !type.isInstance(value)) {
        // in such case default Spring back end for EhCache throws IllegalStateException which interrupts
        // intercepted method invocation
        String msg = "Cached value is not of required type [" + type.getName() + "]: " + value;
        LOGGER.error(msg, new IllegalStateException(msg));
        return null;
    }

    LOGGER.info("Cache hit. Get by key {} and type {}  from cache {} value '{}'",
            new Object[] { key, type, cache.getName(), value });
    return (T) value;
}

From source file:blue.lapis.pore.impl.PoreWorld.java

@Override
@SuppressWarnings("unchecked")
public Collection<Entity> getEntitiesByClasses(final Class<?>... classes) {
    return Collections2.filter(getEntities(), new Predicate<Entity>() {
        @Override// www.  j  av a  2s  .  c om
        public boolean apply(@Nullable Entity entity) {
            for (Class<?> clazz : classes) {
                if (clazz.isInstance(entity)) {
                    return true;
                }
            }

            return false;
        }
    });
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

public boolean isInstance(final String objectId, final Class<? extends TropixObject> clazz) {
    final TropixObject object = loadTropixObject(objectId);
    return clazz.isInstance(object);
}

From source file:de.matzefratze123.heavyspleef.commands.base.CommandManagerService.java

protected void executeCommand(CommandContext context) {
    Method method = context.getCommand().getCommandMethod();
    Object instance = context.getCommand().getCommandClassInstance();

    boolean accessible = method.isAccessible();
    method.setAccessible(true);//from  w ww .j  a v  a2 s  .c  o m

    //Analyse the method
    //Default method format is: methodName(CommandContext)

    try {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            //No parameters in this method, so just invoke it
            method.invoke(instance);
        } else {
            Object[] parameterValues = new Object[parameterTypes.length];

            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];

                if (parameterType == CommandContext.class) {
                    parameterValues[i] = context;
                } else if (plugin.getClass() == parameterType) {
                    parameterValues[i] = plugin;
                } else if (parameterType.isPrimitive()) {
                    parameterValues[i] = getDefaultPrimitiveValue(parameterType);
                } else {
                    for (Object arg : args) {
                        if (parameterType.isInstance(arg)) {
                            parameterValues[i] = arg;
                            break;
                        }
                    }
                }
            }

            method.invoke(instance, parameterValues);
        }
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();

        if (cause instanceof CommandException) {
            ((CommandException) cause).sendToPlayer(context.getSender());
        } else {
            logger.log(Level.SEVERE,
                    "Unhandled exception executing command \"" + context.getCommand().getName() + "\"", cause);
        }
    } catch (IllegalAccessException | IllegalArgumentException e) {
        logger.log(Level.SEVERE,
                "Could not invoke command method for '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } catch (Exception e) {
        logger.log(Level.SEVERE,
                "Unhandled exception executing command '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } finally {
        method.setAccessible(accessible);
    }
}

From source file:com.drisoftie.action.async.BaseAsyncAction.java

@SuppressWarnings("unchecked")
@Override//  w  w w . j ava2s. c  o  m
public <HandlerT> HandlerT getHandlerImpl(Class<HandlerT> clazz) {
    HandlerT result = null;
    for (ActionBinding<ViewT> binding : bindings) {
        if (clazz.isInstance(binding.actionHandler)) {
            result = (HandlerT) binding.actionHandler;
            break;
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Utility method that checks if obj is an instance of targetType.
 * /*from w w  w  .  ja v  a  2s . c  om*/
 * @param obj
 *            Object to check
 * @param targetType
 *            Class type for which to check
 * 
 * @return true if obj is an instance of targetType
 * 
 * @throws InvalidRequestException
 *             if obj is not an instance of targetType.
 */
@SuppressWarnings("rawtypes")
public static boolean isInstanceOf(Object obj, Class targetType) throws InvalidRequestException {
    if (targetType.isInstance(obj)) {
        return true;
    } else {
        Object[] notInstanceOfArgs = { targetType.getName(), obj.getClass().getName() };
        MessageFormat form = new MessageFormat(resourceBundle.getString("error.notInstanceOf"));
        throw new InvalidRequestException(form.format(notInstanceOfArgs));
    }
}

From source file:com.drisoftie.action.async.BaseAsyncAction.java

@SuppressWarnings("unchecked")
@Override/*w  w  w. j av a 2  s .  c o  m*/
public <HandlerT> HandlerT getHandlerImpl(ViewT view, Class<HandlerT> clazz) {
    HandlerT result = null;
    for (ActionBinding<ViewT> binding : bindings) {
        if (binding.view == view && clazz.isInstance(binding.actionHandler)) {
            result = (HandlerT) binding.actionHandler;
            break;
        }
    }
    return result;
}

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

public static <T> T convertJsonObject(JSONObject jsonObject, Class<T> desiredClass, JsonObjectParser<T> parser,
        Class<?> unknownObjectClass, JsonObjectParser<?> unknownObjectParser, String discriminationName,
        JsonObjectParserTable parserTable) throws IOException {

    if (desiredClass.equals(JSONObject.class)) {
        return cast(jsonObject);
    }/*from  w w  w .  j a va  2 s  .c o m*/

    final String discriminationValue = getDiscriminationValue(jsonObject, discriminationName);

    if (parser != null) {
        return parser.parseJsonObject(jsonObject, null, discriminationName, discriminationValue);
    }

    final JsonObjectParser<?> parserFromDiscriminationValue = parserTable.get(discriminationValue);
    if (parserFromDiscriminationValue != null) {
        Object parsedObject = parserFromDiscriminationValue.parseJsonObject(jsonObject, null,
                discriminationName, discriminationValue);
        if (desiredClass.isInstance(parsedObject)) {
            return cast(parsedObject);
        } else {
            return null;
        }
    }

    if (unknownObjectClass != null && desiredClass.isAssignableFrom(unknownObjectClass)) {
        return cast(
                unknownObjectParser.parseJsonObject(jsonObject, null, discriminationName, discriminationValue));
    }

    return null;
}

From source file:org.opencb.commons.datastore.core.ObjectMap.java

protected <N extends Number> List<N> getAsNumberList(String field, Class<N> clazz, Function<String, N> parser,
        String separator) {//from   ww w. j  a v  a 2s .  c o  m
    List list = getAsList(field, separator);

    if (list.isEmpty()) {
        List<N> emptyList = Collections.<N>emptyList();
        put(field, emptyList);
        return emptyList;
    } else {
        boolean valid = true;
        for (Object o : list) {
            if (!clazz.isInstance(o)) {
                valid = false;
                break;
            }
        }
        if (valid) {
            return list;
        } else {
            List<N> numericList = new ArrayList<>(list.size());
            for (Object o : list) {
                if (clazz.isInstance(o)) {
                    numericList.add(clazz.cast(o));
                } else {
                    numericList.add(parser.apply(o.toString()));
                }
            }
            return numericList;
        }
    }
}