Example usage for java.lang Class isInterface

List of usage examples for java.lang Class isInterface

Introduction

In this page you can find the example usage for java.lang Class isInterface.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInterface();

Source Link

Document

Determines if the specified Class object represents an interface type.

Usage

From source file:ReflectUtil.java

/**
 * Returns a set of all interfaces implemented by class supplied. This includes all
 * interfaces directly implemented by this class as well as those implemented by
 * superclasses or interface superclasses.
 * /*from   w  w w  . j  a v a 2  s. c  om*/
 * @param clazz
 * @return all interfaces implemented by this class
 */
public static Set<Class<?>> getImplementedInterfaces(Class<?> clazz) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();

    if (clazz.isInterface())
        interfaces.add(clazz);

    while (clazz != null) {
        for (Class<?> iface : clazz.getInterfaces())
            interfaces.addAll(getImplementedInterfaces(iface));
        clazz = clazz.getSuperclass();
    }

    return interfaces;
}

From source file:com.espertech.esper.util.PopulateUtil.java

public static Object instantiatePopulateObject(Map<String, Object> objectProperties, Class topClass,
        EngineImportService engineImportService) throws ExprValidationException {

    Class applicableClass = topClass;
    if (topClass.isInterface()) {
        applicableClass = findInterfaceImplementation(objectProperties, topClass, engineImportService);
    }/*from  w w  w  .j av a  2 s.  c o m*/

    Object top;
    try {
        top = applicableClass.newInstance();
    } catch (RuntimeException e) {
        throw new ExprValidationException(
                "Exception instantiating class " + applicableClass.getName() + ": " + e.getMessage(), e);
    } catch (InstantiationException e) {
        throw new ExprValidationException(getMessageExceptionInstantiating(applicableClass), e);
    } catch (IllegalAccessException e) {
        throw new ExprValidationException(
                "Illegal access to construct class " + applicableClass.getName() + ": " + e.getMessage(), e);
    }

    populateObject(topClass.getSimpleName(), 0, topClass.getSimpleName(), objectProperties, top,
            engineImportService, null, null);

    return top;
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

/**
 * Based on the given class, properly instructs the ProxyFactory proxies.
 * For additional sanity checks on the passed classes, check the methods
 * below./*from  w w w .ja v a  2  s.  co  m*/
 * 
 * @see #containsUnrelatedClasses(Class[])
 * @see #removeParents(Class[])
 * @param factory
 * @param classes
 */
public static void configureFactoryForClass(ProxyFactory factory, Class<?>[] classes) {
    if (ObjectUtils.isEmpty(classes))
        return;

    for (int i = 0; i < classes.length; i++) {
        Class<?> clazz = classes[i];

        if (clazz.isInterface()) {
            factory.addInterface(clazz);
        } else {
            factory.setTargetClass(clazz);
            factory.setProxyTargetClass(true);
        }
    }
}

From source file:Util.java

/**
 * Return true if class a is either equivalent to class b, or if class a is a subclass of class b, i.e. if a either
 * "extends" or "implements" b. Note tht either or both "Class" objects may represent interfaces.
 * //from w ww .  j  a v a2s.  co  m
 * @param a
 *            class
 * @param b
 *            class
 * @return true if a == b or a extends b or a implements b
 */
@SuppressWarnings("rawtypes")
public static boolean isSubclass(Class<?> a, Class<?> b) {
    // We rely on the fact that for any given java class or
    // primtitive type there is a unqiue Class object, so
    // we can use object equivalence in the comparisons.
    if (a == b) {
        return true;
    }
    if (a == null || b == null) {
        return false;
    }
    for (Class x = a; x != null; x = x.getSuperclass()) {
        if (x == b) {
            return true;
        }
        if (b.isInterface()) {
            Class[] interfaces = x.getInterfaces();
            for (Class anInterface : interfaces) {
                if (isSubclass(anInterface, b)) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:hermes.impl.LoaderSupport.java

/**
 * Return ClassLoader given the list of ClasspathConfig instances. The
 * resulting loader can then be used to instantiate providers from those
 * libraries./* w ww . ja  v  a2  s  .  com*/
 */
static List lookForFactories(final List loaderConfigs, final ClassLoader baseLoader) throws IOException {
    final List rval = new ArrayList();

    for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) {
        final ClasspathConfig lConfig = (ClasspathConfig) iter.next();

        if (lConfig.getFactories() != null) {
            log.debug("using cached " + lConfig.getFactories());

            for (StringTokenizer tokens = new StringTokenizer(lConfig.getFactories(), ","); tokens
                    .hasMoreTokens();) {
                rval.add(tokens.nextToken());
            }
        } else if (lConfig.isNoFactories()) {
            log.debug("previously scanned " + lConfig.getJar());
        } else {
            Runnable r = new Runnable() {
                public void run() {
                    final List localFactories = new ArrayList();
                    boolean foundFactory = false;
                    StringBuffer factoriesAsString = null;

                    try {
                        log.debug("searching " + lConfig.getJar());

                        ClassLoader l = createClassLoader(loaderConfigs, baseLoader);
                        JarFile jarFile = new JarFile(lConfig.getJar());
                        ProgressMonitor monitor = null;
                        int entryNumber = 0;

                        if (HermesBrowser.getBrowser() != null) {
                            monitor = new ProgressMonitor(HermesBrowser.getBrowser(),
                                    "Looking for factories in " + lConfig.getJar(), "Scanning...", 0,
                                    jarFile.size());
                            monitor.setMillisToDecideToPopup(0);
                            monitor.setMillisToPopup(0);
                            monitor.setProgress(0);
                        }

                        for (Enumeration iter = jarFile.entries(); iter.hasMoreElements();) {
                            ZipEntry entry = (ZipEntry) iter.nextElement();
                            entryNumber++;

                            if (monitor != null) {
                                monitor.setProgress(entryNumber);
                                monitor.setNote("Checking entry " + entryNumber + " of " + jarFile.size());
                            }

                            if (entry.getName().endsWith(".class")) {
                                String s = entry.getName().substring(0, entry.getName().indexOf(".class"));

                                s = s.replaceAll("/", ".");

                                try {
                                    if (s.startsWith("hermes.browser") || s.startsWith("hermes.impl")
                                            || s.startsWith("javax.jms")) {
                                        // NOP
                                    } else {
                                        Class clazz = l.loadClass(s);

                                        if (!clazz.isInterface()) {

                                            if (implementsOrExtends(clazz, ConnectionFactory.class)) {

                                                foundFactory = true;
                                                localFactories.add(s);

                                                if (factoriesAsString == null) {
                                                    factoriesAsString = new StringBuffer();
                                                    factoriesAsString.append(clazz.getName());
                                                } else {
                                                    factoriesAsString.append(",").append(clazz.getName());
                                                }
                                                log.debug("found " + clazz.getName());
                                            }
                                        }

                                        /**
                                         * TODO: remove Class clazz = l.loadClass(s);
                                         * Class[] interfaces = clazz.getInterfaces();
                                         * for (int i = 0; i < interfaces.length; i++) {
                                         * if
                                         * (interfaces[i].equals(TopicConnectionFactory.class) ||
                                         * interfaces[i].equals(QueueConnectionFactory.class) ||
                                         * interfaces[i].equals(ConnectionFactory.class)) {
                                         * foundFactory = true; localFactories.add(s);
                                         * if (factoriesAsString == null) {
                                         * factoriesAsString = new
                                         * StringBuffer(clazz.getName()); } else {
                                         * factoriesAsString.append(",").append(clazz.getName()); }
                                         * log.debug("found " + clazz.getName()); } }
                                         */
                                    }
                                } catch (Throwable t) {
                                    // NOP
                                }
                            }
                        }
                    } catch (IOException e) {
                        log.error("unable to access jar/zip " + lConfig.getJar() + ": " + e.getMessage(), e);
                    }

                    if (!foundFactory) {
                        lConfig.setNoFactories(true);
                    } else {
                        lConfig.setFactories(factoriesAsString.toString());
                        rval.addAll(localFactories);
                    }

                }
            };

            r.run();

        }
    }

    return rval;
}

From source file:org.red5.server.api.ScopeUtils.java

public static Object getScopeService(IScope scope, Class intf, Class defaultClass, boolean checkHandler) {
    if (scope == null || intf == null) {
        return null;
    }//from   w ww.  ja  v  a 2s.com
    // We expect an interface
    assert intf.isInterface();

    if (scope.hasAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName())) {
        // Return cached service
        return scope
                .getAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName());
    }

    Object handler = null;
    if (checkHandler) {
        IScope current = scope;
        while (current != null) {
            IScopeHandler scopeHandler = current.getHandler();
            if (intf.isInstance(scopeHandler)) {
                handler = scopeHandler;
                break;
            }

            if (!current.hasParent())
                break;

            current = current.getParent();
        }
    }

    if (handler == null && IScopeService.class.isAssignableFrom(intf)) {
        // We got an IScopeService, try to lookup bean
        Field key = null;
        Object serviceName = null;
        try {
            key = intf.getField("BEAN_NAME");
            serviceName = key.get(null);
            if (!(serviceName instanceof String))
                serviceName = null;
        } catch (Exception e) {
            log.debug("No string field 'BEAN_NAME' in that interface");
        }

        if (serviceName != null)
            handler = getScopeService(scope, (String) serviceName, defaultClass);
    }

    if (handler == null && defaultClass != null) {
        try {
            handler = defaultClass.newInstance();
        } catch (Exception e) {
            log.error(e);
        }
    }

    // Cache service
    scope.setAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName(), handler);
    return handler;
}

From source file:org.eclipse.e4.emf.internal.xpath.helper.ValueUtils.java

public static int getCollectionHint(Class<?> clazz) {
    if (clazz.isArray()) {
        return 1;
    }//  ww w.  ja va 2  s  . c o m

    if (Collection.class.isAssignableFrom(clazz)) {
        return 1;
    }

    if (clazz.isPrimitive()) {
        return -1;
    }

    if (clazz.isInterface()) {
        return 0;
    }

    if (Modifier.isFinal(clazz.getModifiers())) {
        return -1;
    }

    return 0;
}

From source file:org.eclipse.wb.internal.rcp.databinding.model.beans.bindables.BeanSupport.java

/**
 * @return {@link PropertyDescriptor} properties for given bean {@link Class}.
 *///from  w  w  w  .  ja v  a2 s .c o m
public static List<PropertyDescriptor> getPropertyDescriptors(Class<?> beanClass) throws Exception {
    List<PropertyDescriptor> descriptors = Lists.newArrayList();
    // handle interfaces
    if (beanClass.isInterface() || Modifier.isAbstract(beanClass.getModifiers())) {
        List<Class<?>> interfaces = CoreUtils.cast(ClassUtils.getAllInterfaces(beanClass));
        for (Class<?> i : interfaces) {
            BeanInfo beanInfo = Introspector.getBeanInfo(i);
            addDescriptors(descriptors, beanInfo.getPropertyDescriptors());
        }
    }
    // handle bean
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    addDescriptors(descriptors, beanInfo.getPropertyDescriptors());
    //
    return descriptors;
}

From source file:ReflectUtil.java

/**
 * Returns an array of Type objects representing the actual type arguments
 * to targetType used by clazz.//ww w  .  j  ava2 s . c om
 * 
 * @param clazz the implementing class (or subclass)
 * @param targetType the implemented generic class or interface
 * @return an array of Type objects or null
 */
public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    classes.add(clazz);

    if (targetType.isInterface())
        classes.addAll(getImplementedInterfaces(clazz));

    Class<?> superClass = clazz.getSuperclass();
    while (superClass != null) {
        classes.add(superClass);
        superClass = superClass.getSuperclass();
    }

    for (Class<?> search : classes) {
        for (Type type : (targetType.isInterface() ? search.getGenericInterfaces()
                : new Type[] { search.getGenericSuperclass() })) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                if (targetType.equals(parameterizedType.getRawType()))
                    return parameterizedType.getActualTypeArguments();
            }
        }
    }

    return null;
}

From source file:org.apache.usergrid.services.ServiceManager.java

@SuppressWarnings("unchecked")
private static Class<Service> findClass(String classname) {

    Class<Service> cls;
    try {// ww  w.j ava2s  .co m
        logger.debug("Attempting to instantiate service class {}", classname);
        cls = (Class<Service>) Class.forName(classname);
        if (cls.isInterface()) {
            cls = (Class<Service>) Class.forName(classname.concat(IMPL));
        }
        if ((cls != null) && !Modifier.isAbstract(cls.getModifiers())) {
            return cls;
        }
    } catch (ClassNotFoundException e1) {
        logger.debug("Could not load class", e1);
    }
    return null;
}