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.autobizlogic.abl.util.BeanUtil.java

private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {
    Field[] allFields = cls.getDeclaredFields();
    for (Field field : allFields) {
        if (!field.getName().equals(fieldName))
            continue;
        int modifiers = field.getModifiers();
        if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers))
            continue;
        if (argClass != null) {
            Class<?> genericType = getGenericType(field.getType());
            if (!genericType.isAssignableFrom(argClass)) {
                String extraInfo = "";
                // If the two classes have the same name, it's probably a classloader problem,
                // so we generate more informative output to help debug
                if (field.getType().getName().equals(argClass.getName())) {
                    extraInfo = ". It looks like the two classes have the same name, so this is "
                            + "probably a classloader issue. The bean field's class comes from "
                            + field.getType().getClassLoader() + ", the other class comes from "
                            + argClass.getClassLoader();
                }/*  www. ja  v  a  2  s .c o m*/
                throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName()
                        + " is of the wrong type (" + field.getType().getName() + ") for the given argument, "
                        + "which is of type " + argClass.getName() + extraInfo);
            }
        }

        return field;
    }

    return null;
}

From source file:com.serotonin.m2m2.module.ModuleRegistry.java

@SuppressWarnings("unchecked")
public static <T extends LicenseEnforcement> List<T> getLicenseEnforcements(Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    for (LicenseEnforcement le : licenseEnforcements) {
        if (clazz.isAssignableFrom(le.getClass()))
            result.add((T) le);/*from   w ww. j av a 2  s. c o  m*/
    }
    return result;
}

From source file:jef.tools.Assert.java

/**
 * classc//from   w w w  .  j av  a2s  .c o m
 * @param obj
 * @param c
 * @param msg
 */
public static void isType(Object obj, Class<?> c, String msg) {
    if (!(c.isAssignableFrom(obj.getClass())))
        throw new ClassCastException(msg);
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

/**
 * Get the method with the given name from the given class, provided that it takes one argument
 * of the provided type.//from w  ww . ja v a  2 s . c  o m
 * @param cls The class who should have (or inherit) the method
 * @param methodName The name of the method
 * @param argClass If provided, the type of the sole argument to the method. If null, no argument is assumed.
 * @param onlyProtectedAndHigher If true, we will ignore private methods in the superclasses.
 * @return The method if found, otherwise null.
 */
private static Method getMethodFromClass(Class<?> cls, String methodName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {

    Method[] allMethods = cls.getDeclaredMethods();
    for (Method meth : allMethods) {
        if (!meth.getName().equals(methodName))
            continue;

        if (onlyProtectedAndHigher) {
            int modifiers = meth.getModifiers();
            if (Modifier.isPrivate(modifiers))
                continue;
        }

        if (argClass != null) {
            Class<?>[] paramTypes = meth.getParameterTypes();
            if (paramTypes.length != 1)
                continue;

            Class<?> genericType = getGenericType(paramTypes[0]);
            if (!genericType.isAssignableFrom(argClass))
                continue;
        }

        // Note that if we're trying to set a value to null, we obviously cannot check the
        // signature for overloading, and therefore we'll return the first method which takes
        // one parameter. I think that's not that unreasonable, but it could conceivably break
        // if someone does funny things with their bean.

        return meth;
    }

    return null;
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Collect all super implementing.//  ww  w. jav  a2  s .c  o m
 *
 * @param <T> the generic type
 * @param clazz the clazz
 * @param implementing the implementing
 * @param list the list
 */
public static <T> void collectAllSuperImplementing(Class<?> clazz, Class<T> implementing, //
        Set<Class<? extends T>> list) {
    if (clazz == null) {
        return;
    }
    if (implementing.isAssignableFrom(clazz) == false) {
        return;
    }
    list.add((Class<? extends T>) clazz);
    collectAllSuperImplementing(clazz.getSuperclass(), implementing, list);
    for (Class<?> ifaces : clazz.getInterfaces()) {
        collectAllSuperImplementing(ifaces, implementing, list);
    }
}

From source file:com.xdtech.core.orm.utils.AssertUtils.java

/**
 * Assert that <code>superType.isAssignableFrom(subType)</code> is <code>true</code>.
 * <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
 * @param superType the super type to check against
 * @param subType the sub type to check//from  w  w  w. j  ava2  s  .  c o m
 * @param message a message which will be prepended to the message produced by
 * the function itself, and which may be used to provide context. It should
 * normally end in a ": " or ". " so that the function generate message looks
 * ok when prepended to it.
 * @throws IllegalArgumentException if the classes are not assignable
 */
public static void isAssignable(Class superType, Class subType, String message) {
    notNull(superType, "Type to check against must not be null");
    if (subType == null || !superType.isAssignableFrom(subType)) {
        throw new IllegalArgumentException(message + subType + " is not assignable to " + superType);
    }
}

From source file:net.femtoparsec.jnlmin.utils.ReflectUtils.java

private static int findCIOneLevelDistance(Class<?> lower, Class<?> upper) {
    if (!upper.isInterface() || lower.isInterface()) {
        throw new IllegalArgumentException(
                String.format("Invalid input class : upper=%s lower=%s", upper, lower));
    }/*from   w  w w  .j a v  a 2s  . co  m*/

    if (lower == upper) {
        return 0;
    }
    if (!upper.isAssignableFrom(lower)) {
        return -1;
    }

    int distance = -1;
    Class<?>[] interfaces = lower.getInterfaces();
    for (Class<?> anInterface : interfaces) {
        int tmp = findIIDistance(anInterface, upper);
        if (tmp >= 0) {
            distance = distance < 0 ? tmp : Math.min(distance, tmp);
        }

        if (distance == 0) {
            break;
        }
    }

    return distance;
}

From source file:fr.inria.atlanmod.neoemf.core.PersistentEObjectAdapter.java

/**
 * Returns the given {@code object} adapted in a specific {@code type}.
 *
 * @param adaptableObject the object to adapt
 * @param adapterType     the class in which the object must be adapted
 *
 * @return an adapted object in the given {@code type}, or {@code null} if the {@code object} cannot be assigned as
 * a {@code type}// w w w. j  a  va2 s  .c o  m
 *
 * @throws NullPointerException if the {@code type} is {@code null}
 */
public static <T extends PersistentEObject> T getAdapter(Object adaptableObject, Class<T> adapterType) {
    if (isNull(adaptableObject)) {
        return null;
    }
    checkNotNull(adapterType);

    Object adapter = null;
    if (adapterType.isInstance(adaptableObject)) {
        adapter = adaptableObject;
    } else if (adaptableObject instanceof InternalEObject) {
        adapter = ADAPTED_OBJECTS_CACHE.getIfPresent(adaptableObject);
        if (isNull(adapter) || !adapterType.isAssignableFrom(adapter.getClass())) {
            adapter = createAdapter(adaptableObject, adapterType);
            ADAPTED_OBJECTS_CACHE.put((InternalEObject) adaptableObject, (PersistentEObject) adapter);
        }
    }

    if (isNull(adapter)) {
        NeoLogger.warn("Unable to create a {0} adapter for this object of type {1}",
                adapterType.getSimpleName(), adaptableObject.getClass().getSimpleName());
    }

    return adapterType.cast(adapter);
}

From source file:com.chiorichan.factory.EvalFactory.java

/**
 * //from ww  w . j a  v a2  s  .c  o  m
 * @param orig
 *            , The original class you would like to override.
 * @param replace
 *            , An instance of the class you are overriding with. Must extend the original class.
 */
public static boolean overrideInterpreter(Class<? extends Interpreter> orig, Interpreter replace) {
    if (!orig.isAssignableFrom(replace.getClass()))
        return false;

    for (Interpreter p : interpreters)
        if (p.getClass().equals(orig))
            interpreters.remove(p);
    register(replace);

    return true;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Gracefully convert given Object to given class given the precondition
 * that both are primitives or one of the classes associated with
 * primitives. eg. If val is of type Double and cls is of type int, return
 * Integer type with appropriate value truncation so that it can be assigned
 * to field with field.set().//from w  w w  . j  a va 2  s . c o m
 *
 * @param cls
 * @param val
 * @return
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
private static Object convertToPrimitiveFieldObj(Object val, Class<?> cls) {
    Class<?> valClass = val.getClass();
    Object result = null;

    try {
        Method getter = null;
        if (cls.isAssignableFrom(Byte.class) || cls.isAssignableFrom(Byte.TYPE)) {
            getter = valClass.getMethod("byteValue");
        } else if (cls.isAssignableFrom(Short.class) || cls.isAssignableFrom(Short.TYPE)) {
            getter = valClass.getMethod("shortValue");
        } else if (cls.isAssignableFrom(Integer.class) || cls.isAssignableFrom(Integer.TYPE)) {
            getter = valClass.getMethod("intValue");
        } else if (cls.isAssignableFrom(Long.class) || cls.isAssignableFrom(Long.TYPE)) {
            getter = valClass.getMethod("longValue");
        } else if (cls.isAssignableFrom(Float.class) || cls.isAssignableFrom(Float.TYPE)) {
            getter = valClass.getMethod("floatValue");
        } else if (cls.isAssignableFrom(Double.class) || cls.isAssignableFrom(Double.TYPE)) {
            getter = valClass.getMethod("doubleValue");
        } else if (cls.isAssignableFrom(Boolean.class) || cls.isAssignableFrom(Boolean.TYPE)) {
            if (val instanceof Boolean) {
                result = val;
            } else {
                throw new TypeMismatchException(cls, val.getClass());
            }
        } else if (cls.isAssignableFrom(Character.class) || cls.isAssignableFrom(Character.TYPE)) {
            if (val instanceof String && ((String) val).length() == 1) {
                char c = ((String) val).charAt(0);
                result = Character.valueOf(c);
            } else if (val instanceof String) {
                throw new TypeMismatchException(
                        "Expected Character, " + "but received String with length other than 1.");
            } else {
                throw new TypeMismatchException(
                        String.format("Expected Character, accept String, but got %s.", val.getClass()));
            }
        }

        if (getter != null) {
            result = getter.invoke(val);
        }
    } catch (NoSuchMethodException e) {
        throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls));
    } catch (SecurityException e) {
        throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls));
    } catch (IllegalAccessException e) {
        throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls));
    } catch (InvocationTargetException e) {
        throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls));
    }

    return result;
}