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:net.minecraftforge.common.crafting.CraftingHelper.java

private static <T> T getClassInstance(String clsName, Class<T> expected) {
    try {//from w  ww  .  java 2s.com
        Class<?> cls = Class.forName(clsName);
        if (!expected.isAssignableFrom(cls))
            throw new JsonSyntaxException("Class '" + clsName + "' is not an " + expected.getSimpleName());
        return (T) cls.newInstance();
    } catch (ClassNotFoundException e) {
        throw new JsonSyntaxException("Could not find " + expected.getSimpleName() + ": " + clsName, e);
    } catch (InstantiationException | IllegalAccessException e) {
        throw new JsonSyntaxException("Could not instantiate " + expected.getSimpleName() + ": " + clsName, e);
    }
}

From source file:cn.guoyukun.spring.utils.AopProxyUtils.java

private static boolean hasAdvice(Object proxy, Class<? extends Advice> adviceClass) {
    if (!AopUtils.isAopProxy(proxy)) {
        return false;
    }//from w  ww . j ava 2  s. co  m
    ProxyFactory proxyFactory = null;
    if (AopUtils.isJdkDynamicProxy(proxy)) {
        proxyFactory = findJdkDynamicProxyFactory(proxy);
    }
    if (AopUtils.isCglibProxy(proxy)) {
        proxyFactory = findCglibProxyFactory(proxy);
    }

    Advisor[] advisors = proxyFactory.getAdvisors();

    if (advisors == null || advisors.length == 0) {
        return false;
    }

    for (Advisor advisor : advisors) {
        if (adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) {
            return true;
        }
    }
    return false;
}

From source file:com.evolveum.midpoint.schema.util.PolicyRuleTypeUtil.java

public static <T extends PolicyActionType> List<T> filterActions(List<PolicyActionType> actions,
        Class<T> clazz) {
    //noinspection unchecked
    return actions.stream().filter(a -> clazz.isAssignableFrom(a.getClass())).map(a -> (T) a)
            .collect(Collectors.toList());
}

From source file:Main.java

public static <T> Set<Class<T>> findClassesAssignableFrom(String packageName, Class<T> assignableFrom)
        throws IOException, ClassNotFoundException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Set<Class<T>> classes = new HashSet<Class<T>>();
    String path = packageName.replace('.', '/');
    URL resource = loader.getResource(path);
    if (resource != null) {
        String filePath = resource.getFile();
        if (filePath != null && new File(filePath).isDirectory()) {
            for (String file : new File(filePath).list()) {
                if (file.endsWith(".class")) {
                    String name = packageName + '.' + file.substring(0, file.indexOf(".class"));
                    Class<T> clazz = (Class<T>) Class.forName(name);
                    if (assignableFrom.isAssignableFrom(clazz))
                        classes.add(clazz);
                }/* w  w w  .  j  av  a  2s .  co m*/
            }
        }
    }
    return classes;
}

From source file:com.norconex.commons.lang.ClassFinder.java

private static String resolveName(ClassLoader loader, String rawName, Class<?> superClass) {
    String className = rawName;//from w  w  w.j a v a2  s.  c  om
    if (!rawName.endsWith(".class") || className.contains("$")) {
        return null;
    }
    className = className.replaceAll("[\\\\/]", ".");
    className = StringUtils.removeStart(className, ".");
    className = StringUtils.removeEnd(className, ".class");

    try {
        Class<?> clazz = loader.loadClass(className);
        // load only concrete implementations
        if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers())
                && superClass.isAssignableFrom(clazz)) {
            return clazz.getName();
        }
    } catch (ClassNotFoundException e) {
        LOG.error("Invalid class: " + className, e);
    } catch (NoClassDefFoundError e) {
        LOG.debug("Invalid class: " + className, e);
    }
    return null;
}

From source file:jp.terasoluna.fw.util.ConvertUtil.java

/**
 * <code>T</code>???//  w  ww .j  av a 2 s .  c  o m
 * <p>
 * <ul>
 *  <li><code>allowsNull</code>?<code>false</code>??
 *        <code>obj</code>?<code>null</code> - 
 *  <li><code>allowsNull</code>?<code>true</code>??
 *        <code>obj</code>?<code>null</code> - <code>null</code>?
 *  <li><code>obj</code>?<code>clazz</code> - ??????
 *  <li><code>obj</code>?<code>clazz</code>????
 *        - <code>ConvertUtils</code>?????????
 * </ul>
 * </p>
 * 
 * @param <T> ??
 * @param obj 
 * @param clazz ??
 * @param allowsNull <code>obj</code>?<code>null</code>?
 *      ??????
 * @return ??
 * @throws IllegalArgumentException <code>clazz</code>?
 *      <code>null</code>??
 *      <code>allowsNull</code>?<code>false</code>??
 *        <code>obj</code>?<code>null</code>??
 *      ?????
 */
@SuppressWarnings("unchecked")
public static <T> T convert(Object obj, Class<T> clazz, boolean allowsNull) throws IllegalArgumentException {

    if (clazz == null) {
        throw new IllegalArgumentException("Argument 'clazz' (" + Object.class.getName() + ") is null");
    }

    if (obj == null) {
        if (!allowsNull) {
            String message = "Unable to cast 'null' to '" + clazz.getName() + "'";
            throw new IllegalArgumentException(message, new ClassCastException(message));
        }
        return null;
    }

    if (clazz.isAssignableFrom(obj.getClass())) {
        return (T) obj;
    }

    Object result = null;
    try {
        result = ConvertUtils.convert(obj.toString(), clazz);
    } catch (ConversionException e) {
        throw new IllegalArgumentException(e);
    }
    return (T) result;
}

From source file:com.haulmont.cuba.web.gui.components.WebComponentsHelper.java

@SuppressWarnings("unchecked")
public static <T extends Component> Collection<T> getComponents(HasComponents container, Class<T> aClass) {
    List<T> res = new ArrayList<>();
    for (Object aContainer : container) {
        Component component = (Component) aContainer;
        if (aClass.isAssignableFrom(component.getClass())) {
            res.add((T) component);//from   w  w  w . j ava  2s.c  om
        } else if (HasComponents.class.isAssignableFrom(component.getClass())) {
            res.addAll(getComponents((HasComponents) component, aClass));
        }
    }

    return res;
}

From source file:org.apache.cxf.dosgi.dsw.OsgiUtils.java

@SuppressWarnings("unchecked")
public static <T> OsgiService<T> getOsgiService(BundleContext bc, Class<T> serviceClass) {
    try {/*from   w  ww. ja  v  a2 s. com*/
        ServiceReference sr = bc.getServiceReference(serviceClass.getName());
        if (sr != null) {
            Object o = bc.getService(sr);
            if (o != null && serviceClass.isAssignableFrom(o.getClass())) {
                return new OsgiService(sr, o);
            }
        }
    } catch (Exception ex) {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Problem retrieving an OSGI service " + serviceClass.getName() + ", exception : "
                    + ex.getMessage());
        }
    }
    return null;
}

From source file:io.neba.core.resourcemodels.mapping.FieldValueMappingCallback.java

/**
 * Converts the given {@link Resource} to the given target type
 * by either {@link import org.apache.sling.api.adapter.Adaptable#adaptTo(Class) adapting}
 * the resource to the target type or by returning the resource itself if the target type
 * is {@link Resource}./*from w  w  w. j a va 2 s . co  m*/
 */
@SuppressWarnings("unchecked")
private static <T> T convert(final Resource resource, final Class<T> targetType) {
    if (resource == null) {
        return null;
    }
    if (targetType.isAssignableFrom(resource.getClass())) {
        return (T) resource;
    }
    return resource.adaptTo(targetType);
}

From source file:com.evolveum.midpoint.prism.xjc.PrismForJAXBUtil.java

private static <T> T getPropertyValue(PrismProperty<?> property, Class<T> requestedType) {
    if (property == null) {
        return null;
    }/*  www .  ja v  a 2  s . c  o m*/

    PrismPropertyValue<?> pvalue = property.getValue();
    if (pvalue == null) {
        return null;
    }

    Object propertyRealValue = pvalue.getValue();

    if (propertyRealValue instanceof Element) {
        if (requestedType.isAssignableFrom(Element.class)) {
            return (T) propertyRealValue;
        }
        Field anyField = getAnyField(requestedType);
        if (anyField == null) {
            throw new IllegalArgumentException("Attempt to read raw property " + property
                    + " while the requested class (" + requestedType + ") does not have 'any' field");
        }
        anyField.setAccessible(true);
        Collection<?> anyElementList = property.getRealValues();
        T requestedTypeInstance;
        try {
            requestedTypeInstance = requestedType.newInstance();
            anyField.set(requestedTypeInstance, anyElementList);
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Instantiate error while reading raw property " + property
                    + ", requested class (" + requestedType + "):" + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(
                    "Illegal access error while reading raw property " + property + ", requested class ("
                            + requestedType + ")" + ", field " + anyField + ": " + e.getMessage(),
                    e);
        }
        return requestedTypeInstance;
    }

    return JaxbTypeConverter.mapPropertyRealValueToJaxb(propertyRealValue);
}