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:hudson.model.Actionable.java

/**
 * Gets the action (first instance to be found) of a specified type that contributed to this build.
 *
 * @param type/*from w w w. jav  a2  s  .  c om*/
 * @return The action or <code>null</code> if no such actions exist.
 * @see #getActions(Class)
 */
public <T extends Action> T getAction(Class<T> type) {
    for (Action a : getActions())
        if (type.isInstance(a))
            return type.cast(a);
    return null;
}

From source file:com.navercorp.pinpoint.web.cluster.DefaultPinpointRouteResponse.java

@Override
public <R extends TBase> R getResponse(Class<R> clazz, R defaultValue) {
    TBase response = getResponse();/*  www  . ja v a2s  . c  om*/

    if (clazz.isInstance(response)) {
        return (R) response;
    }

    return defaultValue;
}

From source file:com.googlecode.psiprobe.tools.logging.logback.LogbackFactoryAccessor.java

/**
 * Attempts to initialize a Logback logger factory via the given class loader.
 *  /*ww  w . j  a  va 2s  . com*/
 * @param cl the ClassLoader to use when fetching the factory
 */
public LogbackFactoryAccessor(ClassLoader cl) throws ClassNotFoundException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    // Get the singleton SLF4J binding, which may or may not be Logback, depending on the            
    // binding.
    Class clazz = cl.loadClass("org.slf4j.impl.StaticLoggerBinder");
    Method m1 = MethodUtils.getAccessibleMethod(clazz, "getSingleton", new Class[] {});
    Object singleton = m1.invoke(null, null);
    Method m = MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory", new Class[] {});
    Object loggerFactory = m.invoke(singleton, null);

    // Check if the binding is indeed Logback
    Class loggerFactoryClass = cl.loadClass("ch.qos.logback.classic.LoggerContext");
    if (!loggerFactoryClass.isInstance(loggerFactory)) {
        throw new RuntimeException("The singleton SLF4J binding was not Logback");
    }
    setTarget(loggerFactory);
}

From source file:com.qatickets.web.common.SessionParamArgumentResolver.java

@SuppressWarnings("rawtypes")
@Override/*from   www  . j  a v  a  2 s.  c  o  m*/
public boolean supportsParameter(MethodParameter parameter) {

    final Annotation[] paramAnns = parameter.getParameterAnnotations();

    for (final Annotation paramAnn : paramAnns) {

        for (Class c : supported) {
            if (c.isInstance(paramAnn)) {
                return true;
            }
        }
    }

    return false;

}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.WrapFactoryConverter.java

/**
 * {@inheritDoc}/*from  w  w  w  .  j  a  va2s  .c  om*/
 */
@Override
public boolean canConvertValueForJava(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass) {
    return value instanceof Wrapper && (expectedClass.isInstance(((Wrapper) value).unwrap())
            || globalDelegate.canConvertValueForJava(((Wrapper) value).unwrap(), expectedClass));
}

From source file:com.mashape.galileo.agent.network.AnalyticsRetryHandler.java

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    Args.notNull(exception, "Exception parameter");
    Args.notNull(context, "HTTP context");

    if (executionCount > this.retryCount) {
        return false;
    }// w  w  w. ja v a  2  s .c  o  m

    if (this.nonRetriableClasses.contains(exception.getClass())) {
        return false;
    } else {
        for (final Class<? extends IOException> rejectException : this.nonRetriableClasses) {
            if (rejectException.isInstance(exception)) {
                return false;
            }
        }
    }

    if (exception instanceof NoHttpResponseException | exception instanceof SocketException
            | exception instanceof NoHttpResponseException) {
        LOGGER.warn(String.format("flush rquest failed, Agent will try to resend the request. reson: (%s)",
                exception.getMessage()));
        return true;
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    if (!clientContext.isRequestSent()) {
        LOGGER.debug("Agent will try to resend the request.");
        return true;
    }

    return false;
}

From source file:org.jenkinsci.plugins.uithemes.rest.model.StatusResponse.java

public <T> T dataTo(Class<T> to) throws IOException {
    if (data == null) {
        return null;
    }/*w  ww . j a v a2s .c  om*/
    if (to.isInstance(data)) {
        return to.cast(data);
    }
    if (data instanceof String) {
        return JSONReadWrite.fromString((String) data, to);
    } else {
        String asString = JSONReadWrite.toString(data);
        return JSONReadWrite.fromString(asString, to);
    }
}

From source file:org.bytesoft.openjtcc.supports.spring.NativeBeanFactoryImpl.java

@SuppressWarnings("unchecked")
public <T> T getBean(Class<T> interfaceClass, String beanId) {
    Object beanInst = this.applicationContext.getBean(beanId);
    if (interfaceClass.isInstance(beanInst) //
            && Compensable.class.isInstance(beanInst)//
    ) {/* w ww.ja va  2s  .  c  om*/
        if (this.transactionManager == null) {
            throw new RuntimeException();
        }

        try {
            if (this.transactionManager.getTransaction() != null) {
                throw new RuntimeException();
            }
        } catch (SystemException ex) {
            throw new RuntimeException(ex);
        }

        NativeCompensableProxy<Serializable> proxy = new NativeCompensableProxy<Serializable>();
        proxy.setBeanName(beanId);
        proxy.setTarget((Compensable<Serializable>) beanInst);
        proxy.setProxyId(atomic.incrementAndGet());
        proxy.setTransactionManager(this.transactionManager);

        ClassLoader classLoader = beanInst.getClass().getClassLoader();
        Class<?>[] interfaces = null;
        if (Compensable.class.equals(interfaceClass)) {
            interfaces = new Class[] { interfaceClass };
        } else {
            interfaces = new Class[] { interfaceClass, Compensable.class };
        }
        Object proxyInst = Proxy.newProxyInstance(classLoader, interfaces, proxy);

        proxy.setFacade((Compensable<Serializable>) proxyInst);

        return interfaceClass.cast(proxyInst);
    }
    throw new RuntimeException();
}

From source file:org.github.aenygmatic.payroll.usecases.postprocessors.EnumMapGeneratingBeanPostProcessor.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(annotationType());
    for (Class<?> interfaceType : interfaceTypes()) {
        Map<E, Object> proxyMap = newEnumMap();
        for (Object bean : beansWithAnnotation.values()) {
            if (interfaceType.isInstance(bean)) {
                addToMap(proxyMap, bean);
            }//from   w ww.  j ava  2s .  c  o  m
        }
        beanFactory.registerSingleton(generateName(interfaceType), proxyMap);
    }
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T extends Fragment> T attach(Activity activity, int containerId, Class<T> fragmentType,
        String tag) {/*w  ww.  ja  va  2  s .  co  m*/
    if (activity == null) {
        throw new IllegalArgumentException("activity is null");
    }
    if (fragmentType == null) {
        throw new IllegalArgumentException("fragmentType is null");
    }
    if (tag == null) {
        throw new IllegalArgumentException("tag is null");
    }

    T result;

    FragmentManager manager = activity.getFragmentManager();
    Fragment fragment = manager.findFragmentByTag(tag);

    if (fragment == null) {
        try {
            result = fragmentType.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException(
                    "fragmentType cannot be instantiated (default constructor is not visible)", e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(
                    "fragmentType cannot be instantiated (instance could not be created)", e);
        }

        manager.beginTransaction().add(containerId, result, tag).commit();
    } else {
        if (!fragmentType.isInstance(fragment)) {
            throw new IllegalArgumentException("Different fragmentType for tag");
        }

        result = (T) fragment;
    }

    return result;
}