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:org.apache.usergrid.services.DBServiceManager.java

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

    Class<Service> cls;
    try {/*w  ww .j a va 2  s  .c  o  m*/
        if (logger.isTraceEnabled()) {
            logger.trace("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) {
        if (logger.isTraceEnabled()) {
            logger.trace("Could not find class", e1);
        }
    }
    return null;
}

From source file:jenkins.plugins.git.MethodUtils.java

/**
 * <p>Retrieves a method whether or not it's accessible. If no such method
 * can be found, return {@code null}.</p>
 *
 * @param cls            The class that will be subjected to the method search
 * @param methodName     The method that we wish to call
 * @param parameterTypes Argument class types
 * @return The method//from w w w.j  a  va  2  s.c om
 */
static Method getMethodImpl(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
    Validate.notNull(cls, "Null class not allowed.");
    Validate.notEmpty(methodName, "Null or blank methodName not allowed.");

    // fast path, check if directly declared on the class itself
    for (final Method method : cls.getDeclaredMethods()) {
        if (methodName.equals(method.getName()) && Arrays.equals(parameterTypes, method.getParameterTypes())) {
            return method;
        }
    }
    if (!cls.isInterface()) {
        // ok, now check if directly implemented on a superclass
        // Java 8: note that super-interface implementations trump default methods
        for (Class<?> klass = cls.getSuperclass(); klass != null; klass = klass.getSuperclass()) {
            for (final Method method : klass.getDeclaredMethods()) {
                if (methodName.equals(method.getName())
                        && Arrays.equals(parameterTypes, method.getParameterTypes())) {
                    return method;
                }
            }
        }
    }
    // ok, now we are looking for an interface method... the most specific one
    // in the event that we have two unrelated interfaces both declaring a method of the same name
    // we will give up and say we could not find the method (the logic here is that we are primarily
    // checking for overrides, in the event of a Java 8 default method, that default only
    // applies if there is no conflict from an unrelated interface... thus if there are
    // default methods and they are unrelated then they don't exist... if there are multiple unrelated
    // abstract methods... well they won't count as a non-abstract implementation
    Method res = null;
    for (final Class<?> klass : (List<Class<?>>) ClassUtils.getAllInterfaces(cls)) {
        for (final Method method : klass.getDeclaredMethods()) {
            if (methodName.equals(method.getName())
                    && Arrays.equals(parameterTypes, method.getParameterTypes())) {
                if (res == null) {
                    res = method;
                } else {
                    Class<?> c = res.getDeclaringClass();
                    if (c == klass) {
                        // match, ignore
                    } else if (c.isAssignableFrom(klass)) {
                        // this is a more specific match
                        res = method;
                    } else if (!klass.isAssignableFrom(c)) {
                        // multiple overlapping interfaces declare this method and there is no common ancestor
                        return null;

                    }
                }
            }
        }
    }
    return res;
}

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

@SuppressWarnings("unchecked")
private static Class<? extends RemoteJsonService> findInterface(Class<?> c) {
    while (c != null) {
        if (c.isInterface() && RemoteJsonService.class.isAssignableFrom(c)) {
            return (Class<RemoteJsonService>) c;
        }/*  ww w.j  a  v a 2  s  .  c o  m*/
        for (final Class<?> i : c.getInterfaces()) {
            final Class<? extends RemoteJsonService> r = findInterface(i);
            if (r != null) {
                return r;
            }
        }
        c = c.getSuperclass();
    }
    return null;
}

From source file:org.rosenvold.spring.convention.ConventionBeanFactory.java

/**
 * Resolve the given autowiring value against the given required type,
 * e.g. an {@link org.springframework.beans.factory.ObjectFactory} value to its actual object result.
 *
 * @param autowiringValue the value to resolve
 * @param requiredType    the type to assign the result to
 * @return the resolved value/*from  w w w . j  a  va  2  s .c  o m*/
 */
public static Object resolveAutowiringValue(Object autowiringValue, Class requiredType) {
    if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) {
        ObjectFactory factory = (ObjectFactory) autowiringValue;
        if (autowiringValue instanceof Serializable && requiredType.isInterface()) {
            autowiringValue = Proxy.newProxyInstance(requiredType.getClassLoader(),
                    new Class[] { requiredType }, new ObjectFactoryDelegatingInvocationHandler(factory));
        } else {
            return factory.getObject();
        }
    }
    return autowiringValue;
}

From source file:au.com.dw.testdatacapturej.reflection.util.ReflectionUtil.java

/**
 * Check if a class has a setter method with parameter signature for the superclass for a field.
 *
 * @param clazz/*  w  ww.  j  av a2 s.c om*/
 * @param methodName
 * @param subclass
 * @return
 */
private static boolean hasSetterMethodForSuperClass(Class<?> clazz, String methodName, Class<?> subclass) {
    boolean hasSetterMethodForSuperClass = false;

    Class<?> superclass = subclass.getSuperclass();
    while (superclass != null) {
        hasSetterMethodForSuperClass = hasSetterMethodForParameterClass(clazz, methodName, superclass);
        if (hasSetterMethodForSuperClass)
            break;

        // handle next superclass in chain or super interfaces
        if (superclass.isInterface()) {
            hasSetterMethodForSuperClass = hasSetterMethodForInterfaces(clazz, methodName, superclass);

            // need to break out of the loop
            superclass = null;
        } else {
            // handle interfaces for superclass
            hasSetterMethodForSuperClass = hasSetterMethodForInterfaces(clazz, methodName, superclass);
            if (!hasSetterMethodForSuperClass) {
                subclass = superclass;
                superclass = subclass.getSuperclass();
            } else {
                superclass = null;
            }
        }
    }
    return hasSetterMethodForSuperClass;
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Check if a class implements an interface class.
 * //from www .j  a va2 s .com
 * @param implementingClass
 *            the implementing class
 * @param interfaceClass
 *            the interface class
 * @param matchNameOnly
 *            true to only do name string comparison, false also compares
 *            the class loader.
 * @return true if yes, false not
 */
public static boolean isImplementingClass(Class<?> implementingClass, final Class<?> interfaceClass,
        final boolean matchNameOnly) {
    if (!interfaceClass.isInterface() || implementingClass.isInterface()
            || implementingClass.equals(interfaceClass)) {
        return false;
    }
    Object result = traverseInheritance(implementingClass, interfaceClass, true, new IClassVisitor<Object>() {

        public Object onVisit(Class<?> clazz) {
            if (matchNameOnly) {
                return clazz.getName().equals(interfaceClass.getName()) ? new Object() : null;
            } else {
                return clazz.equals(interfaceClass) ? new Object() : null;
            }
        }

    });
    return result != null;
}

From source file:com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor.java

private static String resolveInterfaceName(Reference reference, Class<?> beanClass)
        throws IllegalStateException {

    String interfaceName;//  ww w  .j  av  a 2 s  . co m
    if (!"".equals(reference.interfaceName())) {
        interfaceName = reference.interfaceName();
    } else if (!void.class.equals(reference.interfaceClass())) {
        interfaceName = reference.interfaceClass().getName();
    } else if (beanClass.isInterface()) {
        interfaceName = beanClass.getName();
    } else {
        throw new IllegalStateException(
                "The @Reference undefined interfaceClass or interfaceName, and the property type "
                        + beanClass.getName() + " is not a interface.");
    }

    return interfaceName;

}

From source file:io.werval.runtime.util.TypeResolver.java

/**
 * Resolves the generic Type for the {@code targetType} by walking the type hierarchy upwards from the
 * {@code initialType}.//from  w ww  .j  a v  a 2  s.c  o  m
 *
 * @param initialType Initial type
 * @param targetType  Target type
 *
 * @return Generic type
 */
public static Type resolveGenericType(Type initialType, Class<?> targetType) {
    Class<?> rawType;
    if (initialType instanceof ParameterizedType) {
        rawType = (Class<?>) ((ParameterizedType) initialType).getRawType();
    } else {
        rawType = (Class<?>) initialType;
    }

    if (targetType.equals(rawType)) {
        return initialType;
    }

    Type result;
    if (targetType.isInterface()) {
        for (Type superInterface : rawType.getGenericInterfaces()) {
            if (superInterface != null && !superInterface.equals(Object.class)) {
                result = resolveGenericType(superInterface, targetType);
                if (result != null) {
                    return result;
                }
            }
        }
    }

    Type superType = rawType.getGenericSuperclass();
    if (superType != null && !superType.equals(Object.class)) {
        result = resolveGenericType(superType, targetType);
        if (result != null) {
            return result;
        }
    }

    return null;
}

From source file:org.ebayopensource.twin.ElementImpl.java

/** Is c an interface that directly extends i? */
static final boolean isInterfaceExtending(Class<?> c, Class<?> i) {
    if (!c.isInterface())
        return false;
    for (Class<?> d : c.getInterfaces())
        if (i.equals(d))
            return true;
    return false;
}

From source file:org.grouplens.grapht.util.Types.java

/**
 * Return the type distance between the child and parent types. The child type
 * must be a subtype of the parent. The type distance between a class and itself is 0;
 * the distance from a class to one of its immediate supertypes (superclass or a directly
 * implemented interface) is 1; deeper distances are computed recursively.
 * /*from   w w w . j ava 2 s.  c o m*/
 * @param child The child type
 * @param parent The parent type
 * @return The type distance
 * @throws IllegalArgumentException if {@code child} is not a subtype of {@code parent}.
 */
public static int getTypeDistance(@Nonnull Class<?> child, @Nonnull Class<?> parent) {
    Preconditions.notNull("child class", child);
    Preconditions.notNull("parent class", parent);

    if (child.equals(parent)) {
        // fast-path same-class tests
        return 0;
    } else if (!parent.isAssignableFrom(child)) {
        // if child does not extend from the parent, return -1
        throw new IllegalArgumentException("child not a subclass of parent");
    } else if (!parent.isInterface()) {
        // if the parent is not an interface, we only need to follower superclasses
        int distance = 0;
        Class<?> cur = child;
        while (!cur.equals(parent)) {
            distance++;
            cur = cur.getSuperclass();
        }
        return distance;
    } else {
        // worst case, recursively compute the type
        // recursion is safe, as types aren't too deep except in crazy-land
        int minDepth = Integer.MAX_VALUE;
        Class<?> sup = child.getSuperclass();
        if (sup != null && parent.isAssignableFrom(sup)) {
            minDepth = getTypeDistance(sup, parent);
        }
        for (Class<?> iface : child.getInterfaces()) {
            if (parent.isAssignableFrom(iface)) {
                int d = getTypeDistance(iface, parent);
                if (d < minDepth) {
                    minDepth = d;
                }
            }
        }
        // minDepth now holds the depth of the superclass with shallowest depth
        return minDepth + 1;
    }
}