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:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Create a collection of a given type./*from  w  w w.  ja  v a2s .  c  om*/
 * @param type destination class
 * @return Collection
 */
protected Collection allocateCollection(Class type) {
    if (!type.isInterface() && ((type.getModifiers() & Modifier.ABSTRACT) == 0)) {
        try {
            return (Collection) type.newInstance();
        } catch (Exception ex) {
            throw new JXPathInvalidAccessException("Cannot create collection of type: " + type, ex);
        }
    }

    if (type == List.class || type == Collection.class) {
        return new ArrayList();
    }
    if (type == Set.class) {
        return new HashSet();
    }
    throw new JXPathInvalidAccessException("Cannot create collection of type: " + type);
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Retrieves {@link JSONArray} class for deserialization.
 *
 * @param arr Array for which retrieve class.
 * @param dfltCls Default class./*w  w w  .ja va  2 s .  c o m*/
 * @return Class of the passed array.
 * @throws GridException Thrown if any error occurs while deserialization.
 */
private static Class getArrayClass(JSONArray arr, @Nullable Class dfltCls) throws GridException {
    assert arr != null;

    Class cls = null;

    if (arr.size() > 0) {
        boolean isFound = false;

        for (Object elem : arr)
            if (elem instanceof JSONObject) {
                JSONObject obj = (JSONObject) elem;

                if (obj.containsKey(AT_CLASS))
                    if (!isFound) {
                        cls = loadClass(obj, AT_CLASS);

                        isFound = true;
                    } else
                        throw new GridException("JSON array can contain only one element with attribute "
                                + AT_CLASS + ": " + arr);
            }
    }

    if (cls == null)
        if (dfltCls != null)
            cls = dfltCls;
        else
            cls = getDefaultClass(arr);

    assert cls != null;

    if ((cls.isInterface() || Modifier.isAbstract(cls.getModifiers())) && Iterable.class.isAssignableFrom(cls))
        if (Set.class.isAssignableFrom(cls))
            cls = HashSet.class;
        else if (Queue.class.isAssignableFrom(cls))
            cls = LinkedList.class;
        else
            cls = ArrayList.class;

    return cls;
}

From source file:gr.abiss.calipso.tiers.processor.ModelDrivenBeanGeneratingRegistryPostProcessor.java

protected void createService(BeanDefinitionRegistry registry, ModelContext modelContext)
        throws NotFoundException, CannotCompileException {
    if (modelContext.getServiceDefinition() == null) {

        String newBeanClassName = modelContext.getGeneratedClassNamePrefix() + "Service";
        String newBeanRegistryName = StringUtils.uncapitalize(newBeanClassName);

        String newBeanPackage = modelContext.getBeansBasePackage() + ".service";
        // grab the generic types
        List<Class<?>> genericTypes = modelContext.getGenericTypes();

        // extend the base service interface
        Class<?> newServiceInterface = JavassistUtil.createInterface(newBeanPackage + newBeanClassName,
                ModelService.class, genericTypes);
        ArrayList<Class<?>> interfaces = new ArrayList<Class<?>>(1);
        interfaces.add(newServiceInterface);

        // create a service implementation bean
        CreateClassCommand createServiceCmd = new CreateClassCommand(
                newBeanPackage + "impl." + newBeanClassName + "Impl", AbstractModelServiceImpl.class);
        createServiceCmd.setInterfaces(interfaces);
        createServiceCmd.setGenericTypes(genericTypes);
        createServiceCmd.addGenericType(modelContext.getRepositoryType());
        HashMap<String, Object> named = new HashMap<String, Object>();
        named.put("value", newBeanRegistryName);
        createServiceCmd.addTypeAnnotation(Named.class, named);

        // create and register a service implementation bean
        Class<?> serviceClass = JavassistUtil.createClass(createServiceCmd);
        AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(serviceClass).getBeanDefinition();
        registry.registerBeanDefinition(newBeanRegistryName, def);

        // note in context as a dependency to a controller
        modelContext.setServiceDefinition(def);
        modelContext.setServiceInterfaceType(newServiceInterface);
        modelContext.setServiceImplType(serviceClass);

    } else {//w w  w .  j  a  v a  2s  .c om
        Class<?> serviceType = ClassUtils.getClass(modelContext.getServiceDefinition().getBeanClassName());
        // grab the service interface
        if (!serviceType.isInterface()) {
            Class<?>[] serviceInterfaces = serviceType.getInterfaces();
            if (ArrayUtils.isNotEmpty(serviceInterfaces)) {
                for (Class<?> interfaze : serviceInterfaces) {
                    if (ModelService.class.isAssignableFrom(interfaze)) {
                        modelContext.setServiceInterfaceType(interfaze);
                        break;
                    }
                }
            }
        }
        Assert.notNull(modelContext.getRepositoryType(),
                "Found a service bean definition for " + modelContext.getGeneratedClassNamePrefix()
                        + "  but failed to figure out the service interface type.");
    }
}

From source file:org.jsconf.core.ConfigurationFactory.java

public ConfigurationFactory withBean(String path, Class<?> bean, String id, boolean proxy) {
    Map<String, Object> properties = new HashMap<>(2);
    if (StringUtils.hasText(id)) {
        properties.put("\"" + ID + "\"", id);
    }//from  w  w w  .  j a  v  a 2s  . c  o  m
    if (proxy) {
        properties.put("\"" + PROXY + "\"", true);
    }
    if (bean.isInterface()) {
        properties.put("\"" + INTERFACE + "\"", bean.getCanonicalName());
    } else {
        properties.put("\"" + CLASS + "\"", bean.getCanonicalName());
    }
    String[] splitedPath = path.split("/");
    Map<String, Map<String, ? extends Object>> object = new HashMap<>(2);
    object.put(splitedPath[splitedPath.length - 1], properties);
    for (int i = splitedPath.length - 2; i >= 0; i--) {
        Map<String, Map<String, ? extends Object>> child = object;
        object = new HashMap<>(2);
        object.put(splitedPath[i], child);
    }
    this.config = this.config.withFallback(ConfigFactory.parseMap(object));
    return this;
}

From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java

/**
 * Returns a new instance of the given class if its a public non abstract class which has a public zero argument constructor otherwise returns null
 *//*from   ww w  .  ja va2s . c o  m*/
protected Object tryCreateInstance(Class<?> type) {
    Object answer = null;
    int modifiers = type.getModifiers();
    if (!Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !type.isInterface()) {
        // if its a concrete class with no args make one
        Constructor<?> constructor = null;
        try {
            constructor = type.getConstructor();
        } catch (NoSuchMethodException e) {
            // ignore
        }
        if (constructor != null) {
            if (Modifier.isPublic(constructor.getModifiers())) {
                try {
                    answer = constructor.newInstance();
                } catch (InstantiationException e) {
                    throw new ProvisionException("Failed to instantiate " + constructor, e);
                } catch (IllegalAccessException e) {
                    throw new ProvisionException("Failed to instantiate " + constructor, e);
                } catch (InvocationTargetException ie) {
                    Throwable e = ie.getTargetException();
                    throw new ProvisionException("Failed to instantiate " + constructor, e);
                }
            }
        }
    }
    return answer;
}

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*www  .jav a2 s  .  co  m*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*from  ww  w .ja va2 s. c  om*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4"));
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

/**
 * Perform the given callback operation on all matching methods of the given
 * class and superclasses (or given interface and super-interfaces).
 * <p>//from  w  w w. j ava2 s.  c om
 * The same named method occurring on subclass and superclass will appear
 * twice, unless excluded by the specified {@link MethodFilter}.
 * 
 * @param clazz
 *            the class to introspect
 * @param mc
 *            the callback to invoke for each method
 * @param mf
 *            the filter that determines the methods to apply the callback
 *            to
 */
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
    // Keep backing up the inheritance hierarchy.
    Method[] methods = getDeclaredMethods(clazz);
    for (Method method : methods) {
        if (mf != null && !mf.matches(method)) {
            continue;
        }
        try {
            mc.doWith(method);
        } catch (IllegalAccessException ex) {
            throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
        }
    }
    if (clazz.getSuperclass() != null) {
        doWithMethods(clazz.getSuperclass(), mc, mf);
    } else if (clazz.isInterface()) {
        for (Class<?> superIfc : clazz.getInterfaces()) {
            doWithMethods(superIfc, mc, mf);
        }
    }
}

From source file:ome.services.graphs.GraphPathBean.java

/**
 * If the given property of the given class is actually declared by an interface that it implements,
 * find the name of the interface that first declares the property.
 * @param className the name of an {@link IObject} class
 * @param propertyName the name of a property of the class
 * @return the interface declaring the property, or {@code null} if none
 *//*from www . j av a2  s  . c  o  m*/
private Class<? extends IObject> getInterfaceForProperty(String className, String propertyName) {
    Class<? extends IObject> interfaceForProperty = null;
    Set<Class<? extends IObject>> interfacesFrom, interfacesTo;
    try {
        interfacesFrom = ImmutableSet
                .<Class<? extends IObject>>of(Class.forName(className).asSubclass(IObject.class));
    } catch (ClassNotFoundException e) {
        log.error("could not load " + IObject.class.getName() + " subclass " + className);
        return null;
    }
    while (!interfacesFrom.isEmpty()) {
        interfacesTo = new HashSet<Class<? extends IObject>>();
        for (final Class<? extends IObject> interfaceFrom : interfacesFrom) {
            if (interfaceFrom.isInterface()
                    && BeanUtils.getPropertyDescriptor(interfaceFrom, propertyName) != null) {
                interfaceForProperty = interfaceFrom;
            }
            for (final Class<?> newInterface : interfaceFrom.getInterfaces()) {
                if (newInterface != IObject.class && IObject.class.isAssignableFrom(newInterface)) {
                    interfacesTo.add(newInterface.asSubclass(IObject.class));
                    classesBySimpleName.put(newInterface.getSimpleName(),
                            newInterface.asSubclass(IObject.class));
                }
            }
        }
        interfacesFrom = interfacesTo;
    }
    return interfaceForProperty == null ? null : interfaceForProperty;
}

From source file:org.force66.beantester.valuegens.ValueGeneratorFactory.java

public ValueGenerator<?> forClass(Class<?> targetClass) {
    Validate.notNull(targetClass, "Null class not allowed");
    ValueGenerator<?> generator = registeredGeneratorMap.get(targetClass);
    if (generator == null) {
        for (ValueGenerator<?> gen : STOCK_GENERATORS) {
            if (gen.canGenerate(targetClass)) {
                registeredGeneratorMap.put(targetClass, gen);
                return gen;
            }/* w ww  .  ja  v  a  2s . c om*/
        }
    } else {
        return generator;
    }

    if (targetClass.isInterface()) {
        InterfaceValueGenerator gen = new InterfaceValueGenerator(targetClass);
        this.registerGenerator(targetClass, gen);
        return gen;
    } else if (Modifier.isAbstract(targetClass.getModifiers())) {
        return null; // generator not possible on abstract classes
    } else if (targetClass.isEnum()) {
        return registerGenericGenerator(targetClass, targetClass.getEnumConstants());
    } else if (targetClass.isArray()) {
        ArrayValueGenerator gen = new ArrayValueGenerator(targetClass, this);
        this.registerGenerator(targetClass, gen);
        return gen;
    } else if (Class.class.equals(targetClass)) {
        return registerGenericGenerator(targetClass, new Object[] { Object.class });
    } else {
        return registerGenericGenerator(targetClass,
                new Object[] { InstantiationUtils.safeNewInstance(this, targetClass) });
    }

}