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:Main.java

private static boolean isCompatible(Class<?> type0, Class<?> type1) {
    if (type0.getName().equals(type1.getName())) {
        return true;
    }/*from www  .  j  av a2s . co  m*/
    if (type0.isPrimitive()) {
        return isCompatible(PRIMITIVE_TO_WRAPPER.get(type0), type1);
    }
    if (type1.isPrimitive()) {
        return isCompatible(type0, PRIMITIVE_TO_WRAPPER.get(type1));
    }
    return type0.isAssignableFrom(type1);
}

From source file:org.synyx.hades.util.ClassUtils.java

/**
 * Returns whether the given object is of one of the given types. Will
 * return {@literal false} for {@literal null}.
 * /*w  w  w  .  j a va  2  s .  c om*/
 * @param object
 * @param types
 * @return
 */
public static boolean isOfType(Object object, Collection<Class<?>> types) {

    if (null == object) {
        return false;
    }

    for (Class<?> type : types) {
        if (type.isAssignableFrom(object.getClass())) {
            return true;
        }
    }

    return false;
}

From source file:Main.java

static boolean isGenericTypeAssignableFrom(ParameterizedType type, Class<?> clazz) {
    Type[] actualTypes = type.getActualTypeArguments();
    for (Type actualType : actualTypes) {
        Class<?> aClazz = null;
        try {/*w  w w  .  ja v a 2  s.co m*/
            aClazz = getClass(actualType);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (aClazz != null && clazz.isAssignableFrom(aClazz)) {
            return true;
        }
    }
    return false;
}

From source file:com.feilong.core.lang.ClassUtil.java

/**
 * Checks if is assignable from.//  w w  w .ja  v a 2  s .  co m
 * 
 * <p>
 * instanceof :? {@code ----->}  <br>
 * isAssignableFrom : {@code ----->} ?
 * </p>
 *
 * @param klass
 *            the klass
 * @param cls
 *            the cls
 * @return  <code>klass</code> null,false<br>
 *          <code>cls</code> null,false
 * @see java.lang.Class#isAssignableFrom(Class)
 * @see org.apache.commons.lang3.ClassUtils#isAssignable(Class, Class)
 * @since 1.4.0
 */
public static boolean isAssignableFrom(Class<?> klass, Class<?> cls) {
    return (null == klass || null == cls) ? false : klass.isAssignableFrom(cls);
}

From source file:com.nextep.designer.synch.ui.SynchUIPlugin.java

@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> serviceInterface) {
    final BundleContext context = getDefault().getBundle().getBundleContext();
    final ServiceReference ref = context.getServiceReference(serviceInterface.getName());
    if (ref != null) {
        Object o = context.getService(ref);
        if (o != null && serviceInterface.isAssignableFrom(o.getClass())) {
            return (T) o;
        }/*from www  .  j  a v a 2s.  c  o  m*/
    }
    throw new ErrorException("Unable to locate requested service " + serviceInterface.getName());
}

From source file:net.buffalo.protocal.util.ClassUtil.java

public static Object convertValue(Object value, Class targetType) {

    if (value.getClass().equals(targetType))
        return value;

    if (targetType.isPrimitive()) {
        targetType = getWrapperClass(targetType);
    }//from  www. j  a  v  a  2  s  .com

    if (targetType.isAssignableFrom(value.getClass()))
        return value;

    if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) {
        try {
            Constructor ctor = targetType.getConstructor(new Class[] { String.class });
            return ctor.newInstance(new Object[] { value.toString() });
        } catch (Exception e) {
            LOGGER.error("convert type error", e);
            throw new RuntimeException(
                    "Cannot convert from " + value.getClass().getName() + " to " + targetType, e);
        }
    }

    if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) {
        Collection collection = (Collection) value;
        Object array = Array.newInstance(targetType.getComponentType(), collection.size());
        int i = 0;
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object val = iter.next();
            Array.set(array, i++, val);
        }

        return array;
    }

    if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) {
        return Arrays.asList((Object[]) value);
    }

    throw new IllegalArgumentException(
            "Cannot convert from " + value.getClass().getName() + " to " + targetType);
}

From source file:Main.java

/**
 * Get all child nodes of parent that implement/subclass the given type.
 * //ww  w. j ava 2  s . co  m
 * @param parent
 *            Parent to search
 * @param nodeType
 *            Type of child to search for
 * @return Array of children of parent that conform to the given nodeType
 */
public static <N extends Node> N[] getChildrenImplementing(Node parent, Class<N> nodeType) {
    if (parent == null) {
        return null;
    }
    NodeList children = parent.getChildNodes();
    if (children == null) {
        return null;
    }
    int count = 0;
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (nodeType.isAssignableFrom(node.getClass())) {
            count++;
        }
    }
    @SuppressWarnings("unchecked")
    N[] array = (N[]) Array.newInstance(nodeType, count);
    for (int i = 0, pos = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (nodeType.isAssignableFrom(node.getClass())) {
            @SuppressWarnings("unchecked")
            N n = (N) node;
            Array.set(array, pos++, n);
        }
    }
    return array;
}

From source file:com.offbynull.coroutines.instrumenter.InternalUtils.java

@SuppressWarnings("unchecked")
static <T extends ContinuationPoint> T validateAndGetContinuationPoint(MethodAttributes attrs, int idx,
        Class<T> expectedType) {
    Validate.notNull(attrs);//  w w  w  .  ja va  2s  .  c  o  m
    Validate.notNull(expectedType);
    Validate.isTrue(idx >= 0);

    List<ContinuationPoint> continuationPoints = attrs.getContinuationPoints();
    Validate.isTrue(idx < continuationPoints.size());

    ContinuationPoint continuationPoint = continuationPoints.get(idx);
    Validate.isTrue(expectedType.isAssignableFrom(continuationPoint.getClass()));

    return (T) continuationPoint;
}

From source file:com.revolsys.util.JavaBeanUtil.java

public static boolean isAssignableFrom(final Collection<Class<?>> classes, final Class<?> objectClass) {
    for (final Class<?> allowedClass : classes) {
        if (allowedClass != null) {
            if (allowedClass.isAssignableFrom(objectClass)) {
                return true;
            }//from w w  w .ja  v  a 2  s.c o  m
        }
    }
    return false;
}

From source file:com.openappengine.utility.ObjectConverter.java

/**
 * Convert the given object value to the given class.
 * @param from The object value to be converted.
 * @param to The type class which the given object should be converted to.
 * @return The converted object value.//from w w w .ja  v a  2s  .c o  m
 * @throws NullPointerException If 'to' is null.
 * @throws UnsupportedOperationException If no suitable converter can be found.
 * @throws RuntimeException If conversion failed somehow. This can be caused by at least
 * an ExceptionInInitializerError, IllegalAccessException or InvocationTargetException.
 */
public static <T> T convert(Object from, Class<T> to) {

    // Null is just null.
    if (from == null) {
        return null;
    }

    // Can we cast? Then just do it.
    if (to.isAssignableFrom(from.getClass())) {
        return to.cast(from);
    }

    // Lookup the suitable converter.
    String converterId = from.getClass().getName() + "_" + to.getName();
    Method converter = CONVERTERS.get(converterId);
    if (converter == null) {
        throw new ObjectConverterException("Cannot convert from " + from.getClass().getName() + " to "
                + to.getName() + ". Requested converter does not exist.");
    }

    // Convert the value.
    try {
        return to.cast(converter.invoke(to, from));
    } catch (Exception e) {
        throw new ObjectConverterException("Cannot convert from " + from.getClass().getName() + " to "
                + to.getName() + ". Conversion failed with " + e.getMessage(), e);
    }
}