Example usage for java.lang Class isAssignableFrom

List of usage examples for java.lang Class isAssignableFrom

Introduction

In this page you can find the example usage for java.lang Class isAssignableFrom.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isAssignableFrom(Class<?> cls);

Source Link

Document

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

Usage

From source file:com.amazonaws.services.simpleworkflow.flow.worker.SynchronousRetrier.java

public void retry(Runnable r) {
    int attempt = 0;
    long startTime = System.currentTimeMillis();
    BackoffThrottler throttler = new BackoffThrottler(retryParameters.getInitialInterval(),
            retryParameters.getMaximumRetryInterval(), retryParameters.getBackoffCoefficient());
    boolean success = false;
    do {// w  ww .  ja v  a  2s .  co  m
        try {
            attempt++;
            throttler.throttle();
            r.run();
            success = true;
            throttler.success();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        } catch (RuntimeException e) {
            throttler.failure();
            for (Class<?> exceptionToNotRetry : exceptionsToNotRetry) {
                if (exceptionToNotRetry.isAssignableFrom(e.getClass())) {
                    throw e;
                }
            }
            long elapsed = System.currentTimeMillis() - startTime;
            if (attempt > retryParameters.getMaximumRetries()
                    || (elapsed >= retryParameters.getExpirationInterval()
                            && attempt > retryParameters.getMinimumRetries())) {
                throw e;
            }
            log.warn("Retrying after failure", e);
        }
    } while (!success);
}

From source file:org.grails.datastore.mapping.reflect.ReflectionUtils.java

/**
 * <p>Tests whether or not the left hand type is compatible with the right hand type in Groovy
 * terms, i.e. can the left type be assigned a value of the right hand type in Groovy.</p>
 * <p>This handles Java primitive type equivalence and uses isAssignableFrom for all other types,
 * with a bit of magic for native types and polymorphism i.e. Number assigned an int.
 * If either parameter is null an exception is thrown</p>
 *
 * @param leftType The type of the left hand part of a notional assignment
 * @param rightType The type of the right hand part of a notional assignment
 * @return True if values of the right hand type can be assigned in Groovy to variables of the left hand type.
 *///from w w w  .ja v  a  2s  .  c  o m
public static boolean isAssignableFrom(final Class<?> leftType, final Class<?> rightType) {
    if (leftType == null) {
        throw new NullPointerException("Left type is null!");
    }
    if (rightType == null) {
        throw new NullPointerException("Right type is null!");
    }
    if (leftType == Object.class) {
        return true;
    }
    if (leftType == rightType) {
        return true;
    }
    // check for primitive type equivalence
    Class<?> r = PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(leftType);
    boolean result = r == rightType;

    if (!result) {
        // If no primitive <-> wrapper match, it may still be assignable
        // from polymorphic primitives i.e. Number -> int (AKA Integer)
        if (rightType.isPrimitive()) {
            // see if incompatible
            r = PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(rightType);
            if (r != null) {
                result = leftType.isAssignableFrom(r);
            }
        } else {
            // Otherwise it may just be assignable using normal Java polymorphism
            result = leftType.isAssignableFrom(rightType);
        }
    }
    return result;
}

From source file:com.wavemaker.runtime.server.ServerUtils.java

/**
 * Try to determine parameter names for a given method. This will check {@link ParamName} attributes and debugging
 * symbols; if no name can be found, a default "arg-&lt;position>" name will be used.
 * //  w w w . j  a v a 2s . c  o  m
 * This will also continue working of method has been loaded by a non-default classloader.
 * 
 * @param method The method to introspect.
 * @return The names of the parameters in an ordered list.
 */
public static List<String> getParameterNames(Method method) {

    int numParams = method.getParameterTypes().length;
    List<String> ret = new ArrayList<String>(numParams);
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    Class<?> paramNameClass = ClassLoaderUtils.loadClass(ParamName.class.getName(),
            method.getDeclaringClass().getClassLoader());

    String[] methodParameterNames;

    try {
        AdaptiveParanamer ap = new AdaptiveParanamer();
        methodParameterNames = ap.lookupParameterNames(method);
        ap = null;
    } catch (ParameterNamesNotFoundException e) {
        logger.info("No parameter names found for method " + method.getName());
        methodParameterNames = new String[numParams];
    }

    for (int i = 0; i < numParams; i++) {
        String paramName = null;

        if (paramName == null) {
            for (Annotation ann : paramAnnotations[i]) {
                if (paramNameClass.isAssignableFrom(ann.annotationType())) {
                    try {
                        Method nameMethod = paramNameClass.getMethod("name");
                        paramName = (String) nameMethod.invoke(ann);
                    } catch (SecurityException e) {
                        throw new WMRuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new WMRuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new WMRuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new WMRuntimeException(e);
                    }

                    break;
                }
            }
        }

        if (paramName == null && methodParameterNames != null) {
            paramName = methodParameterNames[i];
        }

        if (paramName == null) {
            logger.warn("no parameter name information for parameter " + i + ", method: " + method.getName());
            paramName = "arg-" + (i + 1);
        }

        ret.add(paramName);
    }

    return ret;
}

From source file:com.jaspersoft.jasperserver.api.logging.context.impl.BasicLoggingContextProvider.java

public <T extends LoggableEvent> boolean isLoggingEnabled(Class<T> clazz) {
    boolean isEnabled = false;

    for (Class<? extends LoggableEvent> baseClass : enabledLoggingTypesMap.keySet()) {
        if (baseClass.isAssignableFrom(clazz) && enabledLoggingTypesMap.get(baseClass)) {
            isEnabled = true;//from   ww w.  ja v a2  s . c o  m
            break;
        }
    }

    return isEnabled;
}

From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java

private static MethodInfo getMethodInfo(Method[] methods) {
    boolean classIsSame = true;
    boolean methodNameIsSame = true;
    Class<?> cl = null;//from   w  w  w.j  a v  a2 s .co m
    String methodName = null;
    for (Method method : methods) {
        if (classIsSame) {
            Class<?> declaringClass = method.getDeclaringClass();
            if (cl == null) {
                cl = declaringClass;
            } else if (!declaringClass.equals(cl)) {
                if (declaringClass.isAssignableFrom(cl)) {
                    cl = declaringClass;
                } else if (cl.isAssignableFrom(declaringClass)) {
                    // do nothing
                } else {
                    classIsSame = false;
                }
            }
        }

        if (methodNameIsSame) {
            if (methodName == null) {
                methodName = method.getName();
            } else if (!method.getName().equals(methodName)) {
                methodNameIsSame = false;
            }
        }
    }

    String className = cl.getName();
    if (!classIsSame) {
        className += "*";
    }

    if (!methodNameIsSame) {
        methodName += "*";
    }
    return new MethodInfo(className, methodName);
}

From source file:gov.nih.nci.caarray.external.v1_0.AbstractCaArrayEntityTest.java

public static <T> List<Class<? extends T>> findLocalSubclasses(Class<T> c)
        throws ClassNotFoundException, URISyntaxException {
    List<Class<? extends T>> l = new ArrayList<Class<? extends T>>();
    File dir = new File(c.getProtectionDomain().getCodeSource().getLocation().toURI());
    Iterator<File> fi = FileUtils.iterateFiles(dir, new String[] { "class" }, true);
    int prefix = dir.getAbsolutePath().length() + 1;
    int suffix = ".class".length();
    while (fi.hasNext()) {
        File cf = fi.next();//from   w w  w .  j  a v a 2 s  .  com
        String fn = cf.getAbsolutePath();
        try {
            String cn = fn.substring(prefix, fn.length() - suffix);
            if (cn.endsWith("<error>")) {
                continue;
            }
            cn = cn.replace('/', '.');
            System.out.println("cn = " + cn);
            Class tmp = c.getClassLoader().loadClass(cn);
            if ((tmp.getModifiers() & Modifier.ABSTRACT) != 0) {
                continue;
            }
            if (c.isAssignableFrom(tmp)) {
                l.add(tmp);
                System.out.println("added " + cf.getAbsolutePath() + " as " + cn);
            }
        } catch (Exception e) {
            System.err.println(fn);
            e.printStackTrace();
        }
    }
    return l;
}

From source file:org.apache.aries.blueprint.plugin.model.Bean.java

public boolean matches(Class<?> destType, String destId) {
    boolean assignable = destType.isAssignableFrom(this.clazz);
    return assignable && ((destId == null) || id.equals(destId));
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ValueConverter.java

private boolean isCompatibleType(Class<?> targetClass, Object value) {
    return targetClass.isAssignableFrom(value.getClass());
}

From source file:com.autentia.wuija.widget.notification.EventProcessor.java

/**
 * Devuelve si hay registrado o no algn listener del tipo que se pasa como parmetro.
 * /*from   www  .j  av a  2 s . c  o m*/
 * @return true si hay registrado algn listener del tipo especificado, false en otro caso.
 */
public boolean someoneIsListening(Class<? extends WidgetListener> listenerClass) {
    for (WidgetListener listener : listeners) {
        if (listenerClass.isAssignableFrom(listener.getClass())) {
            return true;
        }
    }
    return false;
}

From source file:pl.bristleback.server.bristle.conf.resolver.action.ActionResolver.java

private boolean isDefaultRemoteAction(Class clazz, Method action) {
    if (!DefaultAction.class.isAssignableFrom(clazz)) {
        // this action class does not have default action
        return false;
    }/*from   w ww  .j  a  va2s  .c  om*/
    Method defaultMethod = DefaultAction.class.getMethods()[0];
    if (!defaultMethod.getName().equals(action.getName())) {
        return false;
    }
    Class[] defaultParameterTypes = defaultMethod.getParameterTypes();
    if (defaultParameterTypes.length != action.getParameterTypes().length) {
        return false;
    }
    int parametersLength = defaultParameterTypes.length;
    for (int i = 0; i < parametersLength - 1; i++) {
        Class defaultParameterType = defaultParameterTypes[i];
        if (!defaultParameterType.isAssignableFrom(action.getParameterTypes()[i])) {
            return false;
        }
    }
    Type requiredLastParameterType = action.getGenericParameterTypes()[parametersLength - 1];
    Type actualLastParameterType = null;
    for (int i = 0; i < clazz.getInterfaces().length; i++) {
        Class interfaceOfClass = clazz.getInterfaces()[i];
        if (DefaultAction.class.equals(interfaceOfClass)) {
            Type genericInterface = clazz.getGenericInterfaces()[i];
            if (genericInterface instanceof ParameterizedType) {
                actualLastParameterType = ((ParameterizedType) (genericInterface)).getActualTypeArguments()[1];
            } else {
                actualLastParameterType = Object.class;
            }
        }
    }

    return requiredLastParameterType.equals(actualLastParameterType);
}