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.carrot2.workbench.editors.factory.EditorFactory.java

/**
 * Return <code>true</code> if a given <code>className<code> is assignable
 * to <code>clazz</code>.//from   w w w .j  a va 2s  . c o  m
 */
@SuppressWarnings("unchecked")
private static boolean isCompatible(Class<?> clazz, String className) {
    /*
     * This checking is currently class-name based instead of using
     * runtime-type information (assignability). 
     * Is this because of class-loader problems?
     */

    boolean compatible = clazz.getName().equals(className);

    if (!compatible) {
        List<String> superClasses = convertClassesToClassNames(getAllSuperclasses(clazz));
        compatible = superClasses.contains(className);
    }

    if (!compatible && clazz.isInterface()) {
        compatible = "java.lang.Object".equals(className);
    }

    if (!compatible) {
        List<String> interfaces = convertClassesToClassNames(getAllInterfaces(clazz));
        compatible = interfaces.contains(className);
    }

    return compatible;
}

From source file:org.jgentleframework.context.JGentle.java

/**
 * Removes a given configurable class from registered list.
 * /*w  w  w. j a va2 s.c  o m*/
 * @param interfaze
 *            the interface type of configurable class.
 * @return returns the removed configigurabke class if it existed, otherwise
 *         returns null.
 */
@SuppressWarnings("unchecked")
public static <T> T removeConfigClass(Class<T> interfaze) {

    Assertor.notNull(interfaze);
    if (!interfaze.isInterface()) {
        throw new JGentleRuntimeException(interfaze.toString() + " must be a interface.");
    }
    return (T) JGentle.configObjClassList.remove(interfaze);
}

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

/**
 * ??????? <code>ParameterizedType</code>???
 * @param <T> ???//from www . jav  a2 s  .  c o m
 * @param genericClass ??
 * @param descendantClass <code>genericsClass</code>?? ???
 * @return ??????? <code>ParameterizedType</code>?
 * @throws IllegalStateException <code>descendantClass</code>? ??????????? <code>genercClass</code>
 *             ????? ?????
 */
protected static <T> List<ParameterizedType> getAncestorTypeList(Class<T> genericClass,
        Class<? extends T> descendantClass) throws IllegalStateException {
    List<ParameterizedType> ancestorTypeList = new ArrayList<ParameterizedType>();
    Class<?> clazz = descendantClass;
    boolean isInterface = genericClass.isInterface();

    while (clazz != null) {
        Type type = clazz.getGenericSuperclass();
        if (checkParameterizedType(type, genericClass, ancestorTypeList)) {
            break;
        }

        // ??????
        // ??????
        if (!isInterface) {
            clazz = clazz.getSuperclass();
            continue;
        }
        if (checkInterfaceAncestors(genericClass, ancestorTypeList, clazz)) {
            break;
        }

        // ???????????
        // ????????
        // ?????????????
        // ??????????
        // ???Generics?API?????????????
        // ?????????
        clazz = clazz.getSuperclass();
    }

    // ?????
    // AbstractBLogic<P, R>
    if (ancestorTypeList.isEmpty()) {
        throw new IllegalStateException(
                "Argument 'genericClass'(" + genericClass.getName() + ") does not declare type parameter");
    }

    // ???????????????
    // ??????????
    // ???Generics?API?????????????
    // ?????????
    ParameterizedType targetType = ancestorTypeList.get(ancestorTypeList.size() - 1);
    if (!targetType.getRawType().equals(genericClass)) {
        throw new IllegalStateException("Class(" + descendantClass.getName()
                + ") is not concrete class of Class(" + genericClass.getName() + ")");
    }
    return ancestorTypeList;
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied
 * name and parameter types. Searches all superclasses up to
 * <code>Object</code>.//from   w  w  w  .  j  a v  a  2s . c o  m
 * <p>
 * Returns <code>null</code> if no {@link Method} can be found.
 * 
 * @param clazz the class to introspect
 * @param name the name of the method
 * @param parameterTypes the parameter types of the method (may be
 *            <code>null</code> to indicate any signature)
 * @return the Method object, or <code>null</code> if none found
 */
public static Method findMethod(final Class<?> clazz, final String name, final Class<?>[] parameterTypes) {
    Validate.notNull(clazz, "Class must not be null");
    Validate.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        final Method[] methods = searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods();
        for (final Method method : methods) {
            if (name.equals(method.getName())
                    && (parameterTypes == null || Arrays.equals(parameterTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

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

/**
 * Traverse the inheritance tree of a class, including the class itself.
 * //from w  w  w . j  a  v  a 2  s.  com
 * @param <T>
 *            the type to return as traversal result.
 * @param clazz
 *            the class to traverse
 * @param upTillClass
 *            the top level class to stop at
 * @param includeInterfaces
 *            true to traverse interfaces, false not to
 * @param visitor
 *            the visitor to be called on visiting each class on the
 *            inheritance tree. If the onVisit() method returns null, the
 *            traversal will continue, otherwise it will stop and return the
 *            value as overall result.
 * @return the value returned by the visitor's.
 */
public static <T> T traverseInheritance(Class<?> clazz, Class<?> upTillClass, boolean includeInterfaces,
        IClassVisitor<T> visitor) {
    if (!includeInterfaces && clazz.isInterface()) {
        return null;
    }
    if (upTillClass != null && upTillClass.equals(clazz)) {
        return visitor.onVisit(clazz);
    }
    if (Object.class.equals(clazz)) {
        return null;
    }
    T result = visitor.onVisit(clazz);
    if (result != null) {
        return result;
    }
    for (Class<?> intf : clazz.getInterfaces()) {
        result = traverseInheritance(intf, upTillClass, includeInterfaces, visitor);
        if (result != null) {
            return result;
        }
    }
    Class<?> parentClass = clazz.getSuperclass();
    if (parentClass != null) {
        result = traverseInheritance(parentClass, upTillClass, includeInterfaces, visitor);
    }
    return result;
}

From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java

/**
 * Create a new instance of something of the specified collection type.
 *
 * @param collectionType The collection type.
 * @return the new instance.//  www. ja va2s.c  om
 */
public static Collection newCollectionInstance(Class collectionType) {
    if (Collection.class.isAssignableFrom(collectionType)) {
        Collection collection;
        if ((collectionType.isInterface()) || (Modifier.isAbstract(collectionType.getModifiers()))) {
            if (Set.class.isAssignableFrom(collectionType)) {
                if (SortedSet.class.isAssignableFrom(collectionType)) {
                    collection = new TreeSet();
                } else {
                    collection = new HashSet();
                }
            } else {
                collection = new ArrayList();
            }
        } else {
            try {
                collection = (Collection) collectionType.newInstance();
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Unable to create an instance of " + collectionType.getName() + ".", e);
            }
        }
        return collection;
    } else {
        throw new IllegalArgumentException("Invalid list type: " + collectionType.getName());
    }
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from   www  .  j a  va2 s . c o  m*/
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.warn("Property '" + key + "' has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = findTargetClass(key, classMap);
                            newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                    : newTargetClass;
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    null);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = findTargetClass(key, classMap);
                                targetClass = targetClass == null ? findTargetClass(name, classMap)
                                        : targetClass;
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    null);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied name
 * and parameter types. Searches all superclasses up to {@code Object}.
 * <p>Returns {@code null} if no {@link Method} can be found.
 * @param clazz the class to introspect//from  www .  j  a  v  a 2 s  .  co  m
 * @param name the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods());
        for (Method method : methods) {
            if (name.equals(method.getName())
                    && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.facebook.GraphObjectWrapper.java

private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) {
    if (hasClassBeenVerified(graphObjectClass)) {
        return;/* ww w  .  j  ava  2s.  co m*/
    }

    if (!graphObjectClass.isInterface()) {
        throw new FacebookGraphObjectException(
                "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName());
    }

    Method[] methods = graphObjectClass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        int parameterCount = method.getParameterTypes().length;
        Class<?> returnType = method.getReturnType();
        boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class);

        if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) {
            // Don't worry about any methods from GraphObject or one of its base classes.
            continue;
        } else if (parameterCount == 1 && returnType == Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("set") && methodName.length() > 3) {
                // Looks like a valid setter
                continue;
            }
        } else if (parameterCount == 0 && returnType != Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("get") && methodName.length() > 3) {
                // Looks like a valid getter
                continue;
            }
        }

        throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString());
    }

    recordClassHasBeenVerified(graphObjectClass);
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns 1 if the type is a collection,
 * -1 if it is definitely not/*from   w w w .  j  a  v a2s . c om*/
 * and 0 if it may be a collection in some cases.
 * @param clazz to test
 * @return int
 */
public static int getCollectionHint(Class clazz) {
    if (clazz.isArray()) {
        return 1;
    }

    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;
}