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:ch.sdi.core.impl.data.filter.CollectFilter.java

/**
 * Typesafe extraction of the configured field (property FieldName)
 * <p>//from   w  w  w. j ava 2 s.  co m
 * @param aDataset
 *        dataset to be examined
 * @param aClass
 *        desired class of the field value
 * @return
 */
protected T getFieldValue(Dataset aDataset, Class<T> aClass) {
    Object value = aDataset.get(myFieldName);

    if (value == null) {
        myLog.debug("dataset does not contain a field named " + myFieldName);
        return null;
    }

    if (!(aClass.isInstance(value))) {
        myLog.warn("value of field " + myFieldName + " is not instance of " + aClass.getSimpleName() + ", but: "
                + value.getClass().getName());
        return null;
    }

    return aClass.cast(value);
}

From source file:org.ops4j.pax.wicket.test.spring.ApplicationContextMock.java

public <T> T getBean(Class<T> requiredType) throws BeansException {
    for (Entry<String, Object> bean : beans.entrySet()) {
        if (requiredType.isInstance(bean.getValue())) {
            return (T) bean.getValue();
        }/*from   w w w . ja va  2  s  .co m*/
    }
    throw new IllegalStateException("No bean matching the type found");
}

From source file:com.plutext.converter.MyRetryHandler.java

/**
* Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
* if the given method should be retried.
*//*w w  w .  j a va 2s  . c  o m*/
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
    Args.notNull(exception, "Exception parameter");
    Args.notNull(context, "HTTP context");
    if (executionCount > this.retryCount) {
        // Do not retry if over max retry count
        return false;
    }
    if (this.nonRetriableClasses.contains(exception.getClass())) {
        return false;
    } else {
        for (final Class<? extends IOException> rejectException : this.nonRetriableClasses) {
            if (rejectException.isInstance(exception)) {
                return false;
            }
        }
    }
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final HttpRequest request = clientContext.getRequest();

    if (requestIsAborted(request)) {
        return false;
    }

    try {
        System.out.println("sleeping  " + executionCount);
        Thread.sleep(RETRY_SLEEP_TIME * executionCount);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (handleAsIdempotent(request)) {
        // Retry if the request is considered idempotent
        System.out.println("retry handleAsIdempotent " + executionCount);
        return true;
    }

    if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) {
        // Retry if the request has not been sent fully or
        // if it's OK to retry methods that have been sent
        System.out.println("retry  " + executionCount);
        return true;
    }
    // otherwise do not retry
    System.out.println("do not retry  " + exception.getClass().getName() + exception.getMessage());
    return false;
}

From source file:ductive.console.commands.register.CommandInvoker.java

protected Object execute(CommandContext ctx, MethodCommandTarget target, ParameterType[] paramTypes,
        List<Parameter> params) {
    try {//from   w  w w  . j  ava 2  s  . co m
        Preprocessed pp = preprocess(params);

        Class<?>[] parameters = target.method.getParameterTypes();
        Object[] args = new Object[parameters.length];
        int aidx = 0;
        for (int i = 0; i < parameters.length; ++i) {
            Class<?> param = parameters[i];

            if (Terminal.class.isAssignableFrom(param)) {
                if (!param.isInstance(ctx.terminal))
                    throw new RuntimeException(String.format("method '%s' does not support terminal '%s'",
                            target.method, ctx.terminal));

                args[i] = ctx.terminal;
                continue;
            } else if (TerminalUser.class.isAssignableFrom(param)) {
                args[i] = ctx.user;
                continue;
            }

            ParameterType t = paramTypes[aidx++];
            args[i] = handleParam(pp, t);
        }

        Validate.isTrue(aidx == paramTypes.length);

        // http://stackoverflow.com/questions/2659517/access-exception-when-invoking-method-of-an-anonymous-class-using-java-reflectio
        target.method.setAccessible(true);

        return ReflectionUtils.invokeMethod(target.method, target.bean, args);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.esigate.parser.ParserContextImpl.java

@Override
public <T> T findAncestor(Class<T> type) {
    T result = null;//  w w  w  .  j  a  va 2s  .c  o  m
    for (int i = stack.size() - 1; i > -1; i--) {
        Element currentElement = stack.elementAt(i).element;
        if (type.isInstance(currentElement)) {
            result = type.cast(currentElement);
            break;
        }
    }
    // try with root
    if (result == null && type.isInstance(root.root)) {
        result = type.cast(root.root);
    }

    return result;
}

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

/**
 * Get exact bean./*from   ww  w  . ja va  2s . c o m*/
 *
 * @param name  the bean name
 * @param clazz the expected class
 * @param <T>   the exact type
 * @return exact bean
 * @throws BeansException for any error
 */
protected <T> T getBeanWithType(String name, Class<T> clazz) throws BeansException {
    Object result = getBean(name);
    if (!clazz.isInstance(result)) {
        throw new BeanNotOfRequiredTypeException(name, clazz, result.getClass());
    }

    return clazz.cast(result);
}

From source file:hudson.Util.java

/**
 * Creates a filtered sublist./* w ww. j  a  va 2  s.  c  o  m*/
 * @since 1.176
 */
public static <T> List<T> filter(Iterable<?> base, Class<T> type) {
    List<T> r = new ArrayList<T>();
    for (Object i : base) {
        if (type.isInstance(i)) {
            r.add(type.cast(i));
        }
    }
    return r;
}

From source file:com.bstek.dorado.data.config.definition.ListenableObjectDefinition.java

protected boolean filterGlobalListener(GenericObjectListener<?> listener, Object object) {
    boolean accept = true;
    Class<?> parameterizedType = listener.getParameterizedType();
    if (parameterizedType != null) {
        accept = parameterizedType.isInstance(object);
    }/*from w  ww.j a  v  a 2 s  . co  m*/

    String pattern = listener.getPattern();
    if (accept && StringUtils.isNotEmpty(pattern)) {
        if (object instanceof Namable) {
            accept = PathUtils.match(pattern, ((Namable) object).getName());
            String excludePattern = listener.getExcludePattern();
            if (accept && StringUtils.isNotEmpty(excludePattern)) {
                accept = !PathUtils.match(excludePattern, ((Namable) object).getName());
            }
        } else if (object instanceof Identifiable) {
            accept = PathUtils.match(pattern, ((Identifiable) object).getId());
            String excludePattern = listener.getExcludePattern();
            if (accept && StringUtils.isNotEmpty(excludePattern)) {
                accept = !PathUtils.match(excludePattern, ((Identifiable) object).getId());
            }
        }
    }
    return accept;
}

From source file:com.swordlord.gozer.eventhandler.generic.GozerEventListenerList.java

/**
  * Removes the listener as a listener of the specified type.
  * @param t the type of the listener to be removed
  * @param l the listener to be removed//from  w  ww . j  a v a2 s.  co  m
 */
public synchronized <T extends GozerEventListener> void remove(Class<T> t, T l) {
    if (l == null) {
        throw new NullArgumentException("Listener is null");
    }

    if (!t.isInstance(l)) {
        throw new IllegalArgumentException("Listener " + l + " is not of type " + t);
    }

    // Is l on the list?
    int index = -1;
    for (int i = listenerList.length - 2; i >= 0; i -= 2) {
        if ((listenerList[i] == t) && (listenerList[i + 1].equals(l))) {
            index = i;
            break;
        }
    }

    // If so, remove it
    if (index != -1) {
        Object[] tmp = new Object[listenerList.length - 2];
        // Copy the list up to index

        System.arraycopy(listenerList, 0, tmp, 0, index);
        // Copy from two past the index, up to
        // the end of tmp (which is two elements
        // shorter than the old list)
        if (index < tmp.length) {
            System.arraycopy(listenerList, index + 2, tmp, index, tmp.length - index);
        }

        // set the listener array to the new array or null
        listenerList = (tmp.length == 0) ? NULL_ARRAY : tmp;
    }
}

From source file:de.matzefratze123.heavyspleef.core.FlagManager.java

public boolean isFlagPresent(Class<? extends AbstractFlag<?>> clazz) {
    for (AbstractFlag<?> val : flags.values()) {
        if (clazz.isInstance(val)) {
            return true;
        }/*from   w  w w . ja  v a 2 s. c o m*/
    }

    return false;
}