Example usage for java.lang Class getInterfaces

List of usage examples for java.lang Class getInterfaces

Introduction

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

Prototype

public Class<?>[] getInterfaces() 

Source Link

Document

Returns the interfaces directly implemented by the class or interface represented by this object.

Usage

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.entity.def.DefaultEntityResolver.java

/** {@inheritDoc} */
@Override/*from  w  w w  .j a v a  2 s .c  o m*/
public DescribedEntity<?> resolveEntity(final Class<?> entityType) {
    DefaultEntityResolver.LOGGER.debug("Resolving entity {}", entityType);
    Validate.notNull(entityType, "Entity type may not be null.");
    @SuppressWarnings("unchecked")
    final EntityBuilder<?> builder = DescribedEntity.createBuilder().entityType((Class<Object>) entityType);
    final List<Class<?>> hierarchy = new LinkedList<Class<?>>();
    if (this.searchHierarchyResolver) {
        final Deque<Class<?>> types = new LinkedList<Class<?>>();
        final Set<Class<?>> processed = new HashSet<Class<?>>();
        types.add(entityType);
        while (!types.isEmpty()) {
            final Class<?> next = types.pop();
            hierarchy.add(next);
            final Class<?> superType = next.getSuperclass();
            if (!CheckUtil.isNull(superType) && !processed.contains(superType)) {
                types.add(superType);
            }
            for (final Class<?> interfaceType : next.getInterfaces()) {
                if (!processed.contains(interfaceType)) {
                    types.add(interfaceType);
                }
            }
            processed.add(next);
        }
    } else {
        hierarchy.add(entityType);
    }
    for (final Class<?> type : hierarchy) {
        for (final Annotation a : type.getAnnotations()) {
            builder.addAnnotation(a);
        }
    }
    final DescribedEntity<?> result = builder.build();
    DefaultEntityResolver.LOGGER.debug("Resolved entity {} for type {}", result, entityType);
    return result;
}

From source file:org.polymap.core.runtime.event.AnnotatedEventListener.java

/**
 * //from   ww w.  j ava 2s . c o m
 */
public AnnotatedEventListener(Object handler, Integer mapKey, EventFilter... filters) {
    assert handler != null;
    assert filters != null;
    this.handlerRef = new WeakReference(handler);
    this.handlerClass = handler.getClass();
    this.mapKey = mapKey;

    // find annotated methods
    Queue<Class> types = new ArrayDeque(16);
    types.add(handler.getClass());
    while (!types.isEmpty()) {
        Class type = types.remove();
        if (type.getSuperclass() != null) {
            types.add(type.getSuperclass());
        }
        types.addAll(Arrays.asList(type.getInterfaces()));

        for (Method m : type.getDeclaredMethods()) {
            EventHandler annotation = m.getAnnotation(EventHandler.class);
            if (annotation != null) {
                m.setAccessible(true);

                // annotated method
                AnnotatedMethod am = annotation.delay() > 0 ? new DeferredAnnotatedMethod(m, annotation)
                        : new AnnotatedMethod(m, annotation);

                EventListener listener = am;

                // display thread;
                if (annotation.display()) {
                    // if this is NOT the delegate of the DeferringListener then
                    // check DeferringListener#SessionUICallbackCounter
                    listener = new DisplayingListener(listener);
                }

                // deferred
                // XXX There is a race cond. between the UIThread and the event thread; if the UIThread
                // completes the current request before all display events are handled then the UI
                // is not updated until next user request; DeferringListener handles this by activating
                // UICallBack, improving behaviour - but not really solving in all cases; after 500ms we
                // are quite sure that no more events are pending and UI callback can turned off

                // currenty COMMENTED OUT! see EventManger#SessionEventDispatcher
                if (annotation.delay() > 0 /*|| annotation.display()*/) {
                    int delay = annotation.delay() > 0 ? annotation.delay() : 500;
                    listener = new TimerDeferringListener(listener, delay, 10000);
                }
                // filters
                listener = new FilteringListener(listener,
                        ObjectArrays.concat(am.filters, filters, EventFilter.class));

                // session context; first in chain so that all listener/filters
                // get the proper context
                SessionContext session = SessionContext.current();
                if (session != null) {
                    listener = new SessioningListener(listener, mapKey, session, handlerClass);
                }
                methods.add(listener);
            }
        }
    }
    if (methods.isEmpty()) {
        throw new IllegalArgumentException("No EventHandler annotation found in: " + handler.getClass());
    }
}

From source file:org.eclipse.emf.teneo.extension.DefaultExtensionManager.java

/**
 * Registers an instance for all other extensionpoints it implements if no other instance was already registered for
 * it./*  w  ww.  j a v a  2s . c o m*/
 */
private void registerForAllExtensionPoints(Class<?> cls, ExtensionPoint extensionInstance) {
    if (cls == null) {
        return;
    }

    // for its interfaces
    for (Class<?> interf : cls.getInterfaces()) {
        checkRegister(extensionRegistry.get(interf.getName()), extensionInstance);
    }

    // and for the class itself
    checkRegister(extensionRegistry.get(cls.getName()), extensionInstance);

    // and not the superclass, the check for null is done in the method
    // itself
    registerForAllExtensionPoints(cls.getSuperclass(), extensionInstance);
}

From source file:org.constretto.spring.EnvironmentAnnotationConfigurer.java

@SuppressWarnings("unchecked")
private void removeNonAnnotatedBeansFromAutowireForType(Class lookupClass,
        ConfigurableListableBeanFactory configurableListableBeanFactory) throws ClassNotFoundException {
    List<String> beanNames = new ArrayList<String>();
    Class[] interfaces = lookupClass.getInterfaces();
    for (Class anInterface : interfaces) {
        beanNames.addAll(asList(BeanFactoryUtils
                .beanNamesForTypeIncludingAncestors(configurableListableBeanFactory, anInterface)));
    }/*w  ww  .  j av a2 s  .  com*/
    List<BeanDefinition> potentialMatches = new ArrayList<BeanDefinition>();
    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
        Class beanClass = Class.forName(beanDefinition.getBeanClassName());
        beanDefinition.setAttribute(INCLUDE_IN_COLLECTIONS, beanClass.getInterfaces());
        Environment environmentAnnotation = findEnvironmentAnnotation(beanClass);
        if (environmentAnnotation == null) {
            beanDefinition.setAutowireCandidate(false);
        } else {
            potentialMatches.add(beanDefinition);
        }
    }
    if (potentialMatches.size() == 1) {
        potentialMatches.get(0).setAutowireCandidate(true);
    } else {
        List<BeanDefinition> highestPriorityBeans = new ArrayList<BeanDefinition>();
        for (BeanDefinition potentialMatch : potentialMatches) {
            if (potentialMatch.isAutowireCandidate()) {
                potentialMatch.setAutowireCandidate(false);
                highestPriorityBeans = prioritizeBeans(potentialMatch, highestPriorityBeans);
            }
        }
        if (highestPriorityBeans.size() == 1) {
            highestPriorityBeans.get(0).setAutowireCandidate(true);
        } else {
            List<String> equalPriorityBeans = new ArrayList<String>();
            for (BeanDefinition highestPriorityBean : highestPriorityBeans) {
                equalPriorityBeans.add(highestPriorityBean.getBeanClassName());
            }
            throw new ConstrettoException("More than one bean with the class or interface + ["
                    + lookupClass.getSimpleName()
                    + "] registered with same tag. Could not resolve priority. To fix this, remove one of the following beans "
                    + equalPriorityBeans.toString());
        }
    }
}

From source file:bboss.org.apache.velocity.util.introspection.ClassMap.java

private void populateMethodCacheWithInterface(MethodCache methodCache, Class iface) {
    if (Modifier.isPublic(iface.getModifiers())) {
        populateMethodCacheWith(methodCache, iface);
    }/*from ww w  .j  a  va 2  s  .  com*/
    Class[] supers = iface.getInterfaces();
    for (int i = 0; i < supers.length; i++) {
        populateMethodCacheWithInterface(methodCache, supers[i]);
    }
}

From source file:com.amalto.core.jobox.JobContainer.java

/**
 * Return the {@link JobInvoker} implementation to execute the job.
 *
 * @param jobName A job name//from ww w  .  j  av a2s.co m
 * @param version A job version
 * @return A {@link JobInvoker} implementation depending on job.
 * @throws JobNotFoundException if {@link #getJobInfo(String, String)} returns null (i.e. the job does not exist).
 */
public JobInvoker getJobInvoker(String jobName, String version) {
    JobInfo jobInfo = getJobInfo(jobName, version);
    if (jobInfo == null) {
        throw new JobNotFoundException(jobName, version);
    }
    Class jobClass = getJobClass(jobInfo);
    Class[] interfaces = jobClass.getInterfaces();
    if (interfaces.length > 0) {
        for (Class currentInterface : interfaces) {
            if ("routines.system.api.TalendMDMJob".equals(currentInterface.getName())) { //$NON-NLS-1$
                return new MDMJobInvoker(jobName, version);
            }
        }
    }
    // Default invocation
    return new JobInvoke(jobName, version);
}

From source file:com.moss.nomad.core.packager.Packager.java

private MigrationResources createMigrationResources(MigrationDef def) throws Exception {

    ResolvedMigrationInfo info = resolver.resolve(def);

    /*/*from   w w  w .  j a  v  a 2s  .  c  o m*/
     * Determine the classpath for this migration package.
     */

    List<ResolvedDependencyInfo> dependencyArtifacts = new ArrayList<ResolvedDependencyInfo>();
    dependencyArtifacts.add(new ResolvedDependencyInfo(def.groupId(), def.artifactId(), def.version(),
            def.type(), def.classifier(), info.migrationArtifact()));
    dependencyArtifacts.addAll(info.dependencyArtifacts());

    List<String> handlerClassPath = new ArrayList<String>();
    for (ResolvedDependencyInfo dep : dependencyArtifacts) {

        StringBuilder sb = new StringBuilder();
        sb.append(dep.groupId());
        sb.append("/").append(dep.artifactId());
        sb.append("/").append(dep.version());
        sb.append("/").append(dep.artifactId());

        if (dep.classifier() != null) {
            sb.append("-").append(dep.classifier());
        }

        sb.append("-").append(dep.version());
        sb.append(".").append(dep.type());

        String pathName = sb.toString();

        handlerClassPath.add(pathName);

        if (!dependencies.containsKey(pathName)) {
            dependencies.put(pathName, dep);
        }
    }

    /*
     * Determine which class is the migration handler. There can only be
     * one, any other case will cause an exception to be thrown.
     */

    URL[] cp;
    {
        List<URL> urls = new ArrayList<URL>();

        urls.add(info.migrationArtifact().toURL());

        for (ResolvedDependencyInfo d : dependencyArtifacts) {
            urls.add(d.file().toURL());
        }

        cp = urls.toArray(new URL[0]);
    }

    ClassLoader cl = new URLClassLoader(cp, null);

    List<String> handlerClassNames = new ArrayList<String>();
    for (String jarPath : listJarPaths(info.migrationArtifact())) {

        if (!jarPath.endsWith(".class")) {
            continue;
        }

        String className = jarPath.replaceAll("\\/", ".").substring(0, jarPath.length() - 6);
        Class clazz = cl.loadClass(className);

        for (Class iface : clazz.getInterfaces()) {
            if (iface.getName().equals(MigrationHandler.class.getName())) {
                handlerClassNames.add(className);
                break;
            }
        }
    }

    String handlerClassName;
    if (handlerClassNames.isEmpty()) {

        StringBuilder sb = new StringBuilder();
        sb.append("Could not find an implementation of ");
        sb.append(MigrationHandler.class.getName());
        sb.append(" in migration def jar ");
        sb.append(def.toString());
        sb.append(": there must be exactly one.\n");

        throw new RuntimeException(sb.toString());
    } else if (handlerClassNames.size() > 1) {

        StringBuilder sb = new StringBuilder();
        sb.append("Found more than one implementation of ");
        sb.append(MigrationHandler.class.getName());
        sb.append(" in migration def jar ");
        sb.append(def.toString());
        sb.append(": there must be exactly one.\n");

        for (String n : handlerClassNames) {
            sb.append("    --> ").append(n).append("\n");
        }

        throw new RuntimeException(sb.toString());
    } else {
        handlerClassName = handlerClassNames.get(0);
    }

    return new MigrationResources(handlerClassName, handlerClassPath);
}

From source file:org.gradle.model.internal.manage.schema.extraction.ModelSchemaExtractor.java

public <T> void validateType(Class<T> type) {
    if (!isManaged(type)) {
        throw invalid(type, String.format("must be annotated with %s", Managed.class.getName()));
    }//w  ww  .  j  a  v a  2  s .  c om

    if (!type.isInterface()) {
        throw invalid(type, "must be defined as an interface");
    }

    if (type.getInterfaces().length != 0) {
        throw invalid(type, "cannot extend other types");
    }

    if (type.getTypeParameters().length != 0) {
        throw invalid(type, "cannot be a parameterized type");
    }
}

From source file:org.ff4j.aop.FeatureAdvisor.java

/** {@inheritDoc} */
@Override/*w w  w . j  ava 2s. com*/
public Object postProcessBeforeInitialization(Object bean, String beanName) {
    // Before Initializing allow to check Annotations
    Class<?> target = bean.getClass();
    // Scan interface only once.
    if (!target.isInterface() && target.getInterfaces() != null) {
        // Get Interface
        for (Class<?> currentInterface : target.getInterfaces()) {
            String currentInterfaceName = currentInterface.getCanonicalName();
            if (!currentInterfaceName.startsWith("java.")
                    && !targetInterfacesNames.contains(currentInterfaceName)) {
                targetInterfacesNames.add(currentInterfaceName);
            }
        }
    }
    return bean;
}

From source file:javazoom.jlgui.player.amp.tag.TagInfoFactory.java

/**
 * Load and check class implementation from classname.
 *
 * @param classname// w w  w .ja  v  a2 s.  c om
 * @return TagInfo implementation for given class name
 */
public Class getTagInfoImpl(String classname) {
    Class aClass = null;
    boolean interfaceFound = false;
    if (classname != null) {
        try {
            aClass = Class.forName(classname);
            Class superClass = aClass;
            // Looking for TagInfo interface implementation.
            while (superClass != null) {
                Class[] interfaces = superClass.getInterfaces();
                for (int i = 0; i < interfaces.length; i++) {
                    if ((interfaces[i].getName()).equals("javazoom.jlgui.player.amp.tag.TagInfo")) {
                        interfaceFound = true;
                        break;
                    }
                }
                if (interfaceFound)
                    break;
                superClass = superClass.getSuperclass();
            }
            if (interfaceFound)
                log.info(classname + " loaded");
            else
                log.info(classname + " not loaded");
        } catch (ClassNotFoundException e) {
            log.error("Error : " + classname + " : " + e.getMessage());
        }
    }
    return aClass;
}