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.palantir.ptoss.util.Reflections.java

/**
 * Gets all fields from a given class that are assignable from the target class.
 * @param klass type to query for fields.
 * @param targetClass interface or class that fields must be assignable from to be
 * returned./*from  w w w.j a va  2s  .c o m*/
 * @return all fields in <code>klass</code> that are assignable from
 * <code>targetClass</code>
 * @see Class#isAssignableFrom(Class)
 * @see Class#getDeclaredFields()
 */
public static List<Field> getFieldsOfType(Class<?> klass, Class<?> targetClass) {
    List<Field> fields = Lists.newArrayList();
    for (Field f : klass.getDeclaredFields()) {
        if (targetClass.isAssignableFrom(f.getType())) {
            fields.add(f);
        }
    }
    return fields;
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Gets all inner classes from a given class that are assignable from the target class.
 * @param klass type to query for inner-classes.
 * @param targetClass interface or class that inner classes must be assignable from to be
 * returned./*from  w ww . j  a  v  a2s  . co m*/
 * @return all inner classes in <code>klass</code> that are assignable from
 * <code>targetClass</code>
 * @see Class#isAssignableFrom(Class)
 * @see Class#getDeclaredClasses()
 */
public static List<Class<?>> getTypesOfType(Class<?> klass, Class<?> targetClass) {
    List<Class<?>> classes = Lists.newArrayList();
    for (Class<?> cl : klass.getDeclaredClasses()) {
        if (targetClass.isAssignableFrom(cl)) {
            classes.add(cl);
        }
    }
    return classes;
}

From source file:Main.java

public static long JavaToUnoType(Object obj, long fallbackTypePtr, boolean typeHasFallbackClass)
        throws ClassNotFoundException {
    Class<?> firstCls = obj.getClass();
    Long unoTypePtr = unoTypes.get(firstCls.getName());
    if (unoTypePtr != null) {
        return (long) unoTypePtr;
    } else {/*from  w ww  . j  a v a  2s  .  c om*/
        if (typeHasFallbackClass) {
            Class<?> itf = unoFallbacks.get(fallbackTypePtr);
            if (itf == null) {
                throw new ClassNotFoundException(
                        "BINDING CLASS NOT FOUND (unoFallbacks): Not found for unoTypePtr:" + fallbackTypePtr);
            }
            Class<?> currentCls = firstCls;
            while (true) {
                if ((!itf.equals(currentCls)) && itf.isAssignableFrom(currentCls)) {
                    Long potential = unoTypes.get(currentCls.getName());
                    if (potential != null) {
                        unoTypes.put(firstCls.getName(), potential);
                        return (long) potential;
                    }
                } else {
                    unoTypes.put(firstCls.getName(), fallbackTypePtr);
                    return fallbackTypePtr;
                }
                currentCls = currentCls.getSuperclass();
                if (currentCls == null) {
                    unoTypes.put(firstCls.getName(), fallbackTypePtr);
                    return fallbackTypePtr;
                }
            }
        } else {
            Class<?> currentCls = firstCls;
            while (true) {
                currentCls = currentCls.getSuperclass();
                if (currentCls == null) {
                    unoTypes.put(firstCls.getName(), fallbackTypePtr);
                    return fallbackTypePtr;
                } else {
                    Long potential = unoTypes.get(currentCls.getName());
                    if (potential != null) {
                        if (Modifier.isAbstract(currentCls.getModifiers())) {
                            Long fallbackClassPtr = unoFallbacksClassToPtr.get(currentCls);
                            if (fallbackClassPtr != null) {
                                unoTypes.put(firstCls.getName(), fallbackClassPtr);
                                return fallbackClassPtr;
                            }
                        } else {
                            unoTypes.put(firstCls.getName(), potential);
                            return (long) potential;
                        }
                    }
                }
            }
        }
    }
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static <C> C createInstanceFromClassNameWithArguments(ClassLoader classLoader, String classWithArguments,
        Class<C> expectedType) throws UndeclaredThrowableException {
    try {//  ww  w.  j  av a2 s .c om
        List<String> parameters = toList(escapeValues(classWithArguments.split(";")));
        Class<?> klass = ClassUtils.loadClass(classLoader, shift(parameters));

        if (!expectedType.isAssignableFrom(klass)) {
            throw new IllegalArgumentException(
                    "Class " + expectedType.getName() + " is not assignable from " + klass.getName());
        }

        if (parameters.size() == 0) {
            return expectedType.cast(klass.newInstance());
        }

        String[] args = parameters.toArray(new String[parameters.size()]);
        Constructor<?> constructor = klass.getConstructor(args.getClass());
        return expectedType.cast(constructor.newInstance(new Object[] { args }));
    } catch (ClassNotFoundException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InstantiationException e) {
        throw new UndeclaredThrowableException(e);
    } catch (IllegalAccessException e) {
        throw new UndeclaredThrowableException(e);
    } catch (NoSuchMethodException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InvocationTargetException e) {
        throw new UndeclaredThrowableException(e);
    }
}

From source file:ch.sdi.core.util.ClassUtil.java

/**
 * Lists all types in the given package (recursive) which are annotated by the given annotation and
 * are assignable from given class./*from  w  w  w .  jav a  2s . com*/
 * <p>
 * All types which match the criteria are returned, no further checks (interface, abstract, embedded,
 * etc. are performed.
 * <p>
 *
 * @param aClass
 *        the desired (base) class
 * @param aAnnotation
 *        the desired annotation type
 * @param aRoot
 *        the package name where to start the search. Must not be empty. And not start
 *        with 'org.springframework' (cannot parse springs library itself).
 * @return a list of found types
 */
@SuppressWarnings("unchecked")
public static <T> Collection<Class<T>> findCandidatesByAnnotation(Class<T> aClass,
        Class<? extends Annotation> aAnnotation, String aRoot) {
    Collection<Class<T>> result = new ArrayList<Class<T>>();

    Collection<? extends Class<?>> candidates = findCandidatesByAnnotation(aAnnotation, aRoot);

    candidates.stream().peek(c -> myLog.trace("inspecting candidate " + c.getName()))
            .filter(c -> aClass.isAssignableFrom(c))
            .peek(c -> myLog.debug("candidate " + c.getName() + " is of desired type"))
            .forEach(c -> result.add((Class<T>) c));

    return result;

}

From source file:com.github.rvesse.airline.model.OptionMetadata.java

/**
 * Tries to merge the option metadata together such that the child metadata
 * takes precedence. Not all options can be successfully overridden and an
 * error may be thrown in cases where merging is not possible
 * <p>//from  www  .j  a v a  2 s.c  o  m
 * The following pieces of metadata may be overridden:
 * </p>
 * <ul>
 * <li>Title</li>
 * <li>Description</li>
 * <li>Required</li>
 * <li>Hidden</li>
 * </ul>
 * 
 * @param parent
 *            Parent
 * @param child
 *            Child
 * @return Merged metadata
 */
public static OptionMetadata override(Set<String> names, OptionMetadata parent, OptionMetadata child) {
    // Cannot change option type, arity or names
    if (parent.optionType != child.optionType)
        throw new IllegalArgumentException(
                String.format("Cannot change optionType when overriding option %s", names));
    if (parent.arity != child.arity)
        throw new IllegalArgumentException(
                String.format("Cannot change arity when overriding option %s", names));
    if (!parent.options.equals(child.options))
        throw new IllegalArgumentException(
                String.format("Cannot change option names when overriding option %s", names));

    // Also cannot change the type of the option unless the change is a
    // narrowing conversion
    Class<?> parentType = parent.getJavaType();
    Class<?> childType = child.getJavaType();
    if (!parentType.equals(childType)) {
        if (!parentType.isAssignableFrom(childType)) {
            if (childType.isAssignableFrom(parentType)) {
                // A widening conversion exists but this is illegal however
                // we can give a slightly more informative error in this
                // case
                throw new IllegalArgumentException(String.format(
                        "Cannot change the Java type from %s to %s when overriding option %s as this is a widening type change - only narrowing type changes are permitted",
                        parentType, childType, names));
            } else {
                // No conversion exists
                throw new IllegalArgumentException(String.format(
                        "Cannot change the Java type from %s to %s when overriding option %s - only narrowing type changes where a valid cast exists are permitted",
                        parentType, childType, names));
            }
        }
    }

    // Check for duplicates
    boolean isDuplicate = parent == child || parent.equals(child);

    // Parent must not state it is sealed UNLESS it is a duplicate which can
    // happen when using @Inject to inject options via delegates
    if (parent.sealed && !isDuplicate)
        throw new IllegalArgumentException(
                String.format("Cannot override option %s as parent option declares it to be sealed", names));

    // Child must explicitly state that it overrides otherwise we cannot
    // override UNLESS it is the case that this is a duplicate which
    // can happen when using @Inject to inject options via delegates
    if (!child.overrides && !isDuplicate)
        throw new IllegalArgumentException(
                String.format("Cannot override option %s unless child option sets overrides to true", names));

    OptionMetadata merged;
    //@formatter:off
    merged = new OptionMetadata(child.optionType, child.options,
            child.title != null ? child.title : parent.title,
            child.description != null ? child.description : parent.description, child.arity, child.hidden,
            child.overrides, child.sealed,
            child.restrictions.size() > 0 ? child.restrictions : parent.restrictions, null);
    //@formatter:on

    // Combine both child and parent accessors - this is necessary so the
    // parsed value propagates to all classes in the hierarchy
    Set<Accessor> accessors = new LinkedHashSet<>(child.accessors);
    accessors.addAll(parent.accessors);
    merged.accessors = AirlineUtils.unmodifiableSetCopy(accessors);
    return merged;
}

From source file:com.adaptris.core.runtime.WorkflowManager.java

private static boolean hasInterceptorOfType(List<WorkflowInterceptor> interceptors, Class<?> clz) {
    boolean found = false;
    for (WorkflowInterceptor wi : interceptors) {
        if (clz.isAssignableFrom(wi.getClass())) {
            found = true;//from ww w.j  av  a 2 s . com
            break;
        }
    }
    return found;
}

From source file:fr.mby.utils.spring.aop.support.AopHelper.java

/**
 * Test if an object which implement or extend a parameterized object will be able to handle a specific type.
 * Example : NumberList implements List<Number> { ... } NumberList can store any subtypes of Number : Number,
 * Integer, Long, ... This method return true if called like this supportsType(numberList, Integer.class,
 * List.class) This method return false if called like this supportsType(numberList, String.class, List.class)
 * /*from  ww w . j a  v  a 2  s.c o m*/
 * @param object
 *            the instantiated object we want to test against
 * @param type
 *            the type we want to test if the object can hanldle
 * @param genericIfc
 *            the type of the parameterized object (not the parameter type)
 * @return true if the object implementing the genericIfc supports the specified type
 */
public static <T> boolean supportsType(final Object object, final Class<?> type, final Class<?> genericIfc) {
    Class<?> typeArg = GenericTypeResolver.resolveTypeArgument(object.getClass(), genericIfc);
    if (typeArg == null || typeArg.equals(genericIfc)) {
        final Class<?> targetClass = AopUtils.getTargetClass(object);
        if (targetClass != object.getClass()) {
            typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, genericIfc);
        }
    }

    final boolean test = typeArg == null || typeArg.isAssignableFrom(type);

    final String logMsg;
    if (test) {
        logMsg = "[{}] supports type: [{}] for genericIfc [{}].";
    } else {
        logMsg = "[{}] doesn't support type: [{}] for genericIfc [{}].";
    }

    AopHelper.LOG.debug(logMsg, object.getClass().getSimpleName(), type.getSimpleName(),
            genericIfc.getSimpleName());

    return test;
}

From source file:org.hdiv.web.util.TagUtils.java

/**
 * Determine whether the supplied {@link Tag} has any ancestor tag of the
 * supplied type.//from   www.j  ava  2  s .co  m
 * 
 * @param tag the tag whose ancestors are to be checked
 * @param ancestorTagClass the ancestor {@link Class} being searched for
 * @return <code>true</code> if the supplied {@link Tag} has any ancestor
 *         tag of the supplied type
 * @throws IllegalArgumentException if either of the supplied arguments is
 *             <code>null</code>; or if the supplied
 *             <code>ancestorTagClass</code> is not type-assignable to the
 *             {@link Tag} class
 */
public static Tag getAncestorOfType(Tag tag, Class ancestorTagClass) {

    Assert.notNull(tag, "Tag cannot be null");
    Assert.notNull(ancestorTagClass, "Ancestor tag class cannot be null");
    if (!Tag.class.isAssignableFrom(ancestorTagClass)) {
        throw new IllegalArgumentException(
                "Class '" + ancestorTagClass.getName() + "' is not a valid Tag type");
    }
    Tag ancestor = tag.getParent();
    while (ancestor != null) {
        if (ancestorTagClass.isAssignableFrom(ancestor.getClass())) {
            return ancestor;
        }
        ancestor = ancestor.getParent();
    }
    return null;
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Load a class of a particular type./*  ww  w  .  j  a  v a 2 s  . c  om*/
 * 
 * <p>
 * This uses the {@code type}'s ClassLoader to load the class. If that is
 * not available, it will use the current thread's context class loader.
 * </p>
 * 
 * @param <T>
 *        the desired interface type
 * @param className
 *        the class name that implements the interface
 * @param type
 *        the desired interface
 * @return the class
 */
public static <T> Class<? extends T> loadClass(String className, Class<T> type) {
    try {
        ClassLoader loader = type.getClassLoader();
        if (loader == null) {
            loader = Thread.currentThread().getContextClassLoader();
        }
        Class<?> clazz = loader.loadClass(className);
        if (!type.isAssignableFrom(clazz)) {
            throw new RuntimeException("Class [" + clazz + "] is not a [" + type + ']');
        }
        return clazz.asSubclass(type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unable to load class [" + className + ']', e);
    }
}