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:org.dimitrovchi.conf.service.ServiceParameterUtils.java

static AnnotationParameters annotationParameters() {
    final Class<?>[] stack = ClassResolver.CLASS_RESOLVER.getClassContext();
    final Class<?> caller = stack[3];
    final List<Class<? extends Annotation>> interfaces = new ArrayList<>();
    Class<?> topCaller = null;
    for (int i = 3; i < stack.length && caller.isAssignableFrom(stack[i]); i++) {
        final Class<?> c = stack[i];
        topCaller = stack[i];//from  w w w  .j  av  a 2s  .  com
        if (c.getTypeParameters().length != 0) {
            final TypeVariable<? extends Class<?>> var = c.getTypeParameters()[0];
            final List<Class<? extends Annotation>> bounds = new ArrayList<>(var.getBounds().length);
            for (final Type type : var.getBounds()) {
                if (type instanceof Class<?> && ((Class<?>) type).isAnnotation()) {
                    bounds.add((Class) type);
                }
            }
            if (bounds.size() > interfaces.size()) {
                interfaces.clear();
                interfaces.addAll(bounds);
            }
        }
    }
    final Map<Class<? extends Annotation>, List<Annotation>> annotationMap = new IdentityHashMap<>();
    for (int i = 3; i < stack.length && caller.isAssignableFrom(stack[i]); i++) {
        final Class<?> c = stack[i];
        for (final Class<? extends Annotation> itf : interfaces) {
            final Annotation annotation = c.getAnnotation(itf);
            if (annotation != null) {
                List<Annotation> annotationList = annotationMap.get(itf);
                if (annotationList == null) {
                    annotationMap.put(itf, annotationList = new ArrayList<>());
                }
                annotationList.add(0, annotation);
            }
        }
    }
    return new AnnotationParameters(topCaller, interfaces, annotationMap);
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/** Create an object for the given class and initialize it from conf
*
* @param theClass class of which an object is created
* @param expected the expected parent class or interface
* @return a new object/*from  ww  w . j a  v  a2  s .  c om*/
*/
public static <T> T newInstance(Class<?> theClass, Class<T> expected) {
    T result;
    try {
        if (!expected.isAssignableFrom(theClass)) {
            throw new Exception("Specified class " + theClass.getName() + "" + "does not extend/implement "
                    + expected.getName());
        }
        Class<? extends T> clazz = (Class<? extends T>) theClass;
        Constructor<? extends T> meth = clazz.getDeclaredConstructor(EMPTY_ARRAY);
        meth.setAccessible(true);
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:Main.java

/**
 * Returns all objects of given type and its subtypes
 * @param clazz The class you want to return all of the instances of.
 * @param objects The collection you'd like to search.
 * @return A List of all of the instances of a specific Class found in a Collection.
 *//*from  w w w.ja v a2s.co m*/
public static List getAllInstances(Class clazz, Collection objects) {
    List allInstances = new ArrayList();
    if (objects != null && clazz != null) {
        Iterator objectsIterator = objects.iterator();
        while (objectsIterator.hasNext()) {
            Object instance = objectsIterator.next();
            if (instance != null) {
                if (clazz.isAssignableFrom(instance.getClass())) {
                    allInstances.add(instance);
                }
            }
        }
    }
    return allInstances;
}

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

/**
 * Checks if is assignable from.// w  w w .  ja  v  a 2  s . c o m
 * 
 * <p>
 * instanceof :? ----->  <br>
 * isAssignableFrom : -----> ?
 * </p>
 *
 * @param klass
 *            the klass
 * @param cls
 *            the cls
 * @return true, if checks if is assignable from
 * @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 klass.isAssignableFrom(cls);
}

From source file:com.anathema_roguelike.main.utilities.Utils.java

@SuppressWarnings("unchecked")
public static <T> Collection<T> filterBySubclass(Collection<? super T> unfiltered, Class<T> type) {
    return (Collection<T>) Collections2.filter(unfiltered, item -> {
        if (item != null) {
            return (type.isAssignableFrom(item.getClass()));
        } else {/*from   www. j  ava  2s .  c  o  m*/
            return false;
        }
    });
}

From source file:nz.co.senanque.validationengine.ConvertUtils.java

public static Comparable<?> convertTo(Class<?> clazz, Object obj) {
    if (obj == null) {
        return null;
    }// w  w  w  . j a v a 2  s  .c om
    if (clazz.isAssignableFrom(obj.getClass())) {
        return (Comparable<?>) obj;
    }
    if (clazz.isPrimitive()) {
        if (clazz.equals(Long.TYPE)) {
            clazz = Long.class;
        } else if (clazz.equals(Integer.TYPE)) {
            clazz = Integer.class;
        } else if (clazz.equals(Float.TYPE)) {
            clazz = Float.class;
        } else if (clazz.equals(Double.TYPE)) {
            clazz = Double.class;
        } else if (clazz.equals(Boolean.TYPE)) {
            clazz = Boolean.class;
        }
    }
    if (Number.class.isAssignableFrom(clazz)) {
        if (obj.getClass().equals(String.class)) {
            obj = new Double((String) obj);
        }
        if (!Number.class.isAssignableFrom(obj.getClass())) {
            throw new RuntimeException(
                    "Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
        }
        Number number = (Number) obj;
        if (clazz.equals(Long.class)) {
            return new Long(number.longValue());
        }
        if (clazz.equals(Integer.class)) {
            return new Integer(number.intValue());
        }
        if (clazz.equals(Float.class)) {
            return new Float(number.floatValue());
        }
        if (clazz.equals(Double.class)) {
            return new Double(number.doubleValue());
        }
        if (clazz.equals(BigDecimal.class)) {
            return new BigDecimal(number.doubleValue());
        }
    }
    final String oStr = String.valueOf(obj);
    if (clazz.equals(String.class)) {
        return oStr;
    }
    if (clazz.equals(java.util.Date.class)) {
        return java.sql.Date.valueOf(oStr);
    }
    if (clazz.equals(java.sql.Date.class)) {
        return java.sql.Date.valueOf(oStr);
    }
    if (clazz.equals(Boolean.class)) {
        return new Boolean(oStr);
    }
    throw new RuntimeException("Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
}

From source file:GenericUtils.java

/**
 * Get the Generic definitions from a class for given class without looking
 * super classes./*from  ww  w  . j a  v  a 2  s .  c o m*/
 * @param classFrom Implementing class
 * @param interfaceClz class with generic definition
 * @return null if not found
 */
@SuppressWarnings("unchecked")
public static Type[] getGenericDefinitonsThis(Class classFrom, Class interfaceClz) {

    Type[] genericInterfaces = classFrom.getGenericInterfaces();
    for (Type type : genericInterfaces) {
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;

            if (interfaceClz.isAssignableFrom((Class) pt.getRawType())) {
                return pt.getActualTypeArguments();
            }
        }

    }
    // check if it if available on generic super class
    Type genericSuperclass = classFrom.getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) genericSuperclass;

        if (interfaceClz.equals(pt.getRawType())) {
            return pt.getActualTypeArguments();
        }
    }
    return null;

}

From source file:io.neba.core.util.ReflectionUtil.java

/**
 * @param type must not be <code>null</code>.
 * @return whether the given collection type can be instantiated using {@link #instantiateCollectionType(Class)}.
 *//*from  ww w  . j  a va 2  s .  c om*/
public static boolean isInstantiableCollectionType(Class<?> type) {
    if (type == null) {
        throw new IllegalArgumentException("Method argument type must not be null.");
    }

    for (Class<?> supportedType : getInstantiableCollectionTypes()) {
        if (type.isAssignableFrom(supportedType)) {
            return true;
        }
    }

    return false;
}

From source file:net.sf.nmedit.nomad.core.jpf.JPFServiceInstallerTool.java

@SuppressWarnings("unchecked")
private static Class<Service> lookupServiceImplementationClass(Class<? extends Service> serviceClass,
        String serviceImplementationName, ClassLoader loader) throws ClassNotFoundException {
    Class<?> _class = loader.loadClass(serviceImplementationName);

    if (!serviceClass.isAssignableFrom(_class))
        throw new ClassCastException("Service class is not subclass of " + serviceClass + ": " + _class);

    Class<Service> serviceImplementationClass = (Class<Service>) _class;

    return serviceImplementationClass;
}

From source file:io.coala.factory.ClassUtil.java

/**
 * @param x//from www  .j a  v  a 2  s  . c om
 * @param y
 * @return <tt>true</tt> if x is an ancestor of y or they wrap/represent the
 *         same primitive type, <tt>false</tt> otherwise
 */
public static boolean isAssignableFrom(final Class<?> x, final Class<?> y) {
    return x.isAssignableFrom(y) || isPrimitiveOf(x, y) || isPrimitiveOf(y, x);
}