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.jsconf.core.impl.BeanFactory.java

private BeanDefinitionBuilder buildBeanFromInterface() {
    try {/*ww  w  .j a va2  s . co m*/
        Class<?> classBean = Class.forName(this.interfaceName);
        if (!classBean.isInterface()) {
            throw new BeanCreationException(
                    String.format("Interface is not an interface : %s", this.interfaceName));
        }
        return BeanDefinitionBuilder.genericBeanDefinition(VirtualBean.class).setFactoryMethod("factory")//
                .addConstructorArgValue(classBean).addConstructorArgValue(getAllProperties(this.properties));
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException(String.format("Class not found : %s", this.interfaceName), e);
    }
}

From source file:ch.sourcepond.utils.mdcwrapper.impl.DefaultMdcWrapper.java

@Override
public <T extends Executor> T wrap(final T pExecutor, final Class<T> pInterface) {
    notNull(pExecutor, "Executor to wrapped is null!");
    notNull(pInterface, "Executor interface is null!");
    isTrue(pInterface.isInterface(), "Class specified is not an interface!");
    return createProxyIfNecessary(pExecutor, pInterface.getClassLoader(), pInterface);
}

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

/**
 * Loads injection meta-data/*w  w  w  . j  a va 2s. com*/
 * 
 * @param type
 *            Class
 * @param injectionMetadata
 *            Injection meta-data
 * @param fields
 *            Fields
 */
public static void loadInjectionMetadata(Class<?> type, InjectionMetadata injectionMetadata,
        List<Field> fields) {
    if (type.isInterface()) {
        return;
    }
    for (Class<?> cls = type; !Object.class.equals(cls); cls = cls.getSuperclass()) {
        for (Field field : cls.getDeclaredFields()) {
            field.setAccessible(true);
            List<Field> path = new ArrayList<>(fields);
            path.add(field);

            Inject injectAnnotation = field.getAnnotation(Inject.class);
            if (injectAnnotation != null) {
                if (field.getType().equals(GlobalMetadata.class)
                        || field.getType().equals(CommandGroupMetadata.class)
                        || field.getType().equals(CommandMetadata.class)) {
                    injectionMetadata.metadataInjections.add(new Accessor(path));
                } else {
                    loadInjectionMetadata(field.getType(), injectionMetadata, path);
                }
            }

            try {
                @SuppressWarnings("unchecked")
                Annotation aGuiceInject = field
                        .getAnnotation((Class<? extends Annotation>) Class.forName("com.google.inject.Inject"));
                if (aGuiceInject != null) {
                    if (field.getType().equals(GlobalMetadata.class)
                            || field.getType().equals(CommandGroupMetadata.class)
                            || field.getType().equals(CommandMetadata.class)) {
                        injectionMetadata.metadataInjections.add(new Accessor(path));
                    } else {
                        loadInjectionMetadata(field.getType(), injectionMetadata, path);
                    }
                }
            } catch (ClassNotFoundException e) {
                // this is ok, means Guice is not on the class path, so
                // probably not being used
                // and thus, ok that this did not work.
            } catch (ClassCastException e) {
                // ignore this too, we're doing some funky cross your
                // fingers type reflect stuff to play
                // nicely with Guice
            }

            Option optionAnnotation = field.getAnnotation(Option.class);
            DefaultOption defaultOptionAnnotation = field.getAnnotation(DefaultOption.class);
            if (optionAnnotation != null) {
                OptionType optionType = optionAnnotation.type();
                String name;
                if (!optionAnnotation.title().isEmpty()) {
                    name = optionAnnotation.title();
                } else {
                    name = field.getName();
                }

                List<String> options = AirlineUtils.arrayToList(optionAnnotation.name());
                String description = optionAnnotation.description();

                int arity = optionAnnotation.arity();
                if (arity < 0 && arity != Integer.MIN_VALUE)
                    throw new IllegalArgumentException(String.format("Invalid arity for option %s", name));

                if (optionAnnotation.arity() >= 0) {
                    arity = optionAnnotation.arity();
                } else {
                    Class<?> fieldType = field.getType();
                    if (Boolean.class.isAssignableFrom(fieldType)
                            || boolean.class.isAssignableFrom(fieldType)) {
                        arity = 0;
                    } else {
                        arity = 1;
                    }
                }

                boolean hidden = optionAnnotation.hidden();
                boolean override = optionAnnotation.override();
                boolean sealed = optionAnnotation.sealed();

                // Find and create restrictions
                Map<Class<? extends Annotation>, Set<Integer>> partials = loadPartials(field);
                List<OptionRestriction> restrictions = new ArrayList<OptionRestriction>();
                for (Class<? extends Annotation> annotationClass : RestrictionRegistry
                        .getOptionRestrictionAnnotationClasses()) {
                    Annotation annotation = field.getAnnotation(annotationClass);
                    if (annotation == null)
                        continue;
                    OptionRestriction restriction = RestrictionRegistry.getOptionRestriction(annotationClass,
                            annotation);
                    if (restriction != null) {
                        // Adjust for partial if necessary
                        if (partials.containsKey(annotationClass))
                            restriction = new PartialRestriction(partials.get(annotationClass), restriction);

                        restrictions.add(restriction);
                    }
                }

                //@formatter:off
                OptionMetadata optionMetadata = new OptionMetadata(optionType, options, name, description,
                        arity, hidden, override, sealed, restrictions, path);
                //@formatter:on
                switch (optionType) {
                case GLOBAL:
                    if (defaultOptionAnnotation != null)
                        throw new IllegalArgumentException(String.format(
                                "Field %s which defines a global option cannot be annotated with @DefaultOption as this may only be applied to command options",
                                field));
                    injectionMetadata.globalOptions.add(optionMetadata);
                    break;
                case GROUP:
                    if (defaultOptionAnnotation != null)
                        throw new IllegalArgumentException(String.format(
                                "Field %s which defines a global option cannot be annotated with @DefaultOption as this may only be applied to command options",
                                field));
                    injectionMetadata.groupOptions.add(optionMetadata);
                    break;
                case COMMAND:
                    // Do we also have a @DefaultOption annotation

                    if (defaultOptionAnnotation != null) {
                        // Can't have both @DefaultOption and @Arguments
                        if (injectionMetadata.arguments.size() > 0)
                            throw new IllegalArgumentException(String.format(
                                    "Field %s cannot be annotated with @DefaultOption because there are fields with @Arguments annotations present",
                                    field));
                        // Can't have more than one @DefaultOption
                        if (injectionMetadata.defaultOption != null)
                            throw new IllegalArgumentException(String.format(
                                    "Command type %s has more than one field with @DefaultOption declared upon it",
                                    type));
                        // Arity of associated @Option must be 1
                        if (optionMetadata.getArity() != 1)
                            throw new IllegalArgumentException(String.format(
                                    "Field %s annotated with @DefaultOption must also have an @Option annotation with an arity of 1",
                                    field));
                        injectionMetadata.defaultOption = optionMetadata;
                    }
                    injectionMetadata.commandOptions.add(optionMetadata);
                    break;
                }
            }

            if (optionAnnotation == null && defaultOptionAnnotation != null) {
                // Can't have @DefaultOption on a field without also @Option
                throw new IllegalArgumentException(String.format(
                        "Field %s annotated with @DefaultOption must also have an @Option annotation", field));
            }

            Arguments argumentsAnnotation = field.getAnnotation(Arguments.class);
            if (field.isAnnotationPresent(Arguments.class)) {
                // Can't have both @DefaultOption and @Arguments
                if (injectionMetadata.defaultOption != null)
                    throw new IllegalArgumentException(String.format(
                            "Field %s cannot be annotated with @Arguments because there is a field with @DefaultOption present",
                            field));

                List<String> titles = new ArrayList<>();

                if (!(argumentsAnnotation.title().length == 1 && argumentsAnnotation.title()[0].equals(""))) {
                    titles.addAll(AirlineUtils.arrayToList(argumentsAnnotation.title()));
                } else {
                    titles.add(field.getName());
                }

                String description = argumentsAnnotation.description();

                Map<Class<? extends Annotation>, Set<Integer>> partials = loadPartials(field);
                List<ArgumentsRestriction> restrictions = new ArrayList<>();
                for (Class<? extends Annotation> annotationClass : RestrictionRegistry
                        .getArgumentsRestrictionAnnotationClasses()) {
                    Annotation annotation = field.getAnnotation(annotationClass);
                    if (annotation == null)
                        continue;
                    ArgumentsRestriction restriction = RestrictionRegistry
                            .getArgumentsRestriction(annotationClass, annotation);
                    if (restriction != null) {
                        // Adjust for partial if necessary
                        if (partials.containsKey(annotationClass))
                            restriction = new PartialRestriction(partials.get(annotationClass), restriction);

                        restrictions.add(restriction);
                    }
                }

                //@formatter:off
                injectionMetadata.arguments.add(new ArgumentsMetadata(titles, description, restrictions, path));
                //@formatter:on
            }
        }
    }
}

From source file:com.weibo.api.motan.config.RefererConfig.java

public void setInterface(Class<T> interfaceClass) {
    if (interfaceClass != null && !interfaceClass.isInterface()) {
        throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
    }// www .  j av  a2 s.co  m
    this.interfaceClass = interfaceClass;
}

From source file:com.savoirtech.eos.pattern.factory.AbstractManagedServiceFactory.java

public AbstractManagedServiceFactory(BundleContext bundleContext, Class<T> serviceType) {
    this.serviceType = serviceType;
    this.bundleContext = bundleContext;
    Validate.isTrue(serviceType.isInterface(), "Service type %s is not an interface.", serviceType.getName());
}

From source file:io.coala.factory.ClassUtil.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. See <a//from   w w w .j ava2s. co m
 * href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860"
 * >description</a>
 * 
 * @param genericAncestorType the base class
 * @param concreteDescendantType the child class
 * @return a list of the raw classes for the actual type arguments.
 */
public static <T> List<Class<?>> getTypeArguments(final Class<T> genericAncestorType,
        final Class<? extends T> concreteDescendantType) {
    // sanity check
    if (genericAncestorType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("genericAncestorType");
    if (concreteDescendantType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("concreteDescendantType");

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = concreteDescendantType;
    Class<?> typeClass = getClass(type);

    // start walking up the inheritance hierarchy until we hit parentClass
    while (!genericAncestorType.equals(typeClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.

            if (genericAncestorType.isInterface()) {
                Type intfType = null;
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType
                            && genericAncestorType.equals(((ParameterizedType) intf).getRawType())) {
                        intfType = intf;
                        break;
                    }
                }
                if (intfType == null)
                    type = typeClass.getGenericSuperclass();
                else
                    type = intfType;
            } else
                type = typeClass.getGenericSuperclass();

            if (type == null) {
                if (!typeClass.isInterface()) {
                    LOG.warn("No generic super classes found for child class: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType) {
                        type = intf;
                        // TODO try other interfaces if this one fails?
                        break;
                    }
                }
                if (type == null) {
                    LOG.warn("No generic ancestors found for child interface: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
            }
            // LOG.trace(String.format("Trying generic super of %s: %s",
            // typeClass.getSimpleName(), type));
        } else {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Class<?> rawType = (Class<?>) parameterizedType.getRawType();

            final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            final TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!genericAncestorType.equals(rawType)) {
                type = rawType.getGenericSuperclass();
                // LOG.trace(String.format(
                // "Trying generic super of child %s: %s", rawType,
                // type));
            }
            // else // done climbing the hierarchy
            // LOG.trace("Matched generic " + type + " to ancestor: "
            // + genericAncestorType);
        }
        typeClass = getClass(type);
        // LOG.trace("Trying generic " + typeClass + " from: "
        // + Arrays.asList(typeClass.getGenericInterfaces()));
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    final Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = typeClass.getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }

    // resolve types by chasing down type variables.
    final List<Class<?>> parentTypeArguments = new ArrayList<Class<?>>();
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType))
            baseType = resolvedTypes.get(baseType);

        parentTypeArguments.add(getClass(baseType));
    }
    // LOG.trace(String.format(
    // "Got child %s's type arguments for %s: %s",
    // childClass.getName(), parentClass.getSimpleName(),
    // parentTypeArguments));
    return parentTypeArguments;
}

From source file:com.offbynull.coroutines.instrumenter.asm.ClassLoaderClassInformationRepository.java

@Override
public ClassInformation getInformation(String internalClassName) {
    String className = Type.getObjectType(internalClassName).getClassName();
    Class<?> cls;
    try {/*from ww w  .jav  a  2  s .  com*/
        cls = Class.forName(className, false, classLoader);
    } catch (ClassNotFoundException cfne) {
        return null;
    }

    boolean interfaceMarker = cls.isInterface();

    Class<?>[] interfaceClses = cls.getInterfaces();
    List<String> internalInterfaceNames = new ArrayList<>(interfaceClses.length);
    for (Class<?> interfaceCls : interfaceClses) {
        internalInterfaceNames.add(Type.getInternalName(interfaceCls));
    }

    String internalSuperClassName;
    if (interfaceMarker) {
        // If this is an interface, it needs to mimic how class files are structured. Normally a class file will have its super class
        // set to java/lang/Object if it's an interface. This isn't exposed through the classloader. Not sure why this is like this but
        // if we encounter an interface as the class being accessed through the classloader, always override it to have a "superclass"
        // of java/lang/Object. The classloader itself would return null in this case.
        //
        // This is what ASM does internally as well when it loads info from a classloader.
        internalSuperClassName = Type.getInternalName(Object.class);
    } else {
        Class<?> superCls = cls.getSuperclass();
        internalSuperClassName = superCls == null ? null : Type.getInternalName(superCls);
    }

    return new ClassInformation(internalSuperClassName, internalInterfaceNames, interfaceMarker);
}

From source file:org.grouplens.lenskit.eval.graph.ComponentNodeBuilder.java

private ComponentNodeBuilder(String id, Class<?> type) {
    nodeId = id;
    label = shortClassName(type);
    isInterface = type.isInterface();
}

From source file:com.dianping.resource.io.util.ClassUtils.java

/**
 * Return all interfaces that the given class implements as Set,
 * including ones implemented by superclasses.
 * <p>If the class itself is an interface, it gets returned as sole interface.
 * @param clazz the class to analyze for interfaces
 * @param classLoader the ClassLoader that the interfaces need to be visible in
 * (may be {@code null} when accepting all declared interfaces)
 * @return all interfaces that the given object implements as Set
 *///  w  ww  .j a  v  a 2s  . c o m
public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
    Assert.notNull(clazz, "Class must not be null");
    if (clazz.isInterface() && isVisible(clazz, classLoader)) {
        return Collections.<Class<?>>singleton(clazz);
    }
    Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
    while (clazz != null) {
        Class<?>[] ifcs = clazz.getInterfaces();
        for (Class<?> ifc : ifcs) {
            interfaces.addAll(getAllInterfacesForClassAsSet(ifc, classLoader));
        }
        clazz = clazz.getSuperclass();
    }
    return interfaces;
}

From source file:com.freetmp.common.util.ClassUtils.java

public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
    Assert.notNull(clazz, "Class must not be null");
    if (clazz.isInterface() && isVisible(clazz, classLoader)) {
        return Collections.<Class<?>>singleton(clazz);
    }/*from  w ww. j av a2s  .  c  o m*/
    Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
    while (clazz != null) {
        Class<?>[] ifcs = clazz.getInterfaces();
        for (Class<?> ifc : ifcs) {
            interfaces.addAll(getAllInterfacesForClassAsSet(ifc, classLoader));
        }
        clazz = clazz.getSuperclass();
    }
    return interfaces;
}