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.cruxframework.crux.tools.schema.DefaultSchemaGenerator.java

/**
 * //from   www .j  a va 2 s .  com
 * @param out
 * @param widgetFactory
 */
private void generateEventsForFactory(PrintStream out, Class<?> widgetFactory, Set<String> added) {
    generateEvents(out, added, widgetFactory);
    Class<?> superclass = widgetFactory.getSuperclass();
    if (superclass != null && !superclass.equals(Object.class)) {
        generateEventsForFactory(out, superclass, added);
    }
    Class<?>[] interfaces = widgetFactory.getInterfaces();
    for (Class<?> interfaceClass : interfaces) {
        generateEventsForFactory(out, interfaceClass, added);
    }
}

From source file:org.cruxframework.crux.tools.schema.DefaultSchemaGenerator.java

/**
 * /*from   w ww. j a  v a 2s .  c  om*/
 * @param out
 * @param widgetFactory
 */
private void generateAttributesForFactory(PrintStream out, Class<?> widgetFactory, String library,
        Set<String> added) {
    generateAttributes(out, library, added, widgetFactory);

    Class<?> superclass = widgetFactory.getSuperclass();
    if (superclass != null && !superclass.equals(Object.class)) {
        generateAttributesForFactory(out, superclass, library, added);
    }
    Class<?>[] interfaces = widgetFactory.getInterfaces();
    for (Class<?> interfaceClass : interfaces) {
        generateAttributesForFactory(out, interfaceClass, library, added);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

/** Create MBean for Object.
 * Attempts to create an MBean for the object by searching the
 * package and class name space.  For example an object of the
 * type <PRE>/*w  w w  . j  a  v a2s  .c om*/
 *   class com.acme.MyClass extends com.acme.util.BaseClass
 * </PRE>
 * Then this method would look for the following
 * classes:<UL>
 * <LI>com.acme.MyClassMBean
 * <LI>com.acme.jmx.MyClassMBean
 * <LI>com.acme.util.BaseClassMBean
 * <LI>com.acme.util.jmx.BaseClassMBean
 * </UL>
 * @param o The object
 * @return A new instance of an MBean for the object or null.
 */
public static ModelMBean mbeanFor(Object o) {
    try {
        Class oClass = o.getClass();
        ClassLoader loader = oClass.getClassLoader();

        ModelMBean mbean = null;
        boolean jmx = false;
        Class[] interfaces = null;
        int i = 0;

        while (mbean == null && oClass != null) {
            Class focus = interfaces == null ? oClass : interfaces[i];
            String pName = focus.getPackage().getName();
            String cName = focus.getName().substring(pName.length() + 1);
            String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean";

            try {
                Class mClass = loader.loadClass(mName);
                if (log.isTraceEnabled())
                    log.trace("mbeanFor " + o + " mClass=" + mClass);
                mbean = (ModelMBean) mClass.newInstance();
                mbean.setManagedResource(o, "objectReference");
                if (log.isDebugEnabled())
                    log.debug("mbeanFor " + o + " is " + mbean);
                return mbean;
            } catch (ClassNotFoundException e) {
                if (e.toString().endsWith("MBean")) {
                    if (log.isTraceEnabled())
                        log.trace(e.toString());
                } else
                    log.warn(LogSupport.EXCEPTION, e);
            } catch (Error e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            } catch (Exception e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            }

            if (jmx) {
                if (interfaces != null) {
                    i++;
                    if (i >= interfaces.length) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                } else {
                    interfaces = oClass.getInterfaces();
                    i = 0;
                    if (interfaces == null || interfaces.length == 0) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                }
            }
            jmx = !jmx;
        }
    } catch (Exception e) {
        LogSupport.ignore(log, e);
    }
    return null;
}

From source file:com.silverwrist.dynamo.app.ApplicationContainer.java

private final RegisteredRenderer searchClassRenderers(Class klass) {
    if (klass.isPrimitive() || (klass == Object.class))
        return null; // should have been picked up already

    // look at this level for the class member
    RegisteredRenderer rc = (RegisteredRenderer) (m_class_renderers.get(klass));
    if (rc != null)
        return rc;

    if (klass.isArray()) { // for arrays, use the parallel function to search back over the component
                           // class's hierarchy
        Class component = getUltimateComponent(klass);
        if (component.isPrimitive() || (component == Object.class))
            return null; // no chance this should have been picked up
        String template = StringUtils.replace(klass.getName(), component.getName(), TEMPLATE_CLASSNAME);
        return searchArrayRenderers(component, template);

    } // end if/*from   w ww  .j a  va  2 s.com*/

    // Try all interfaces implemented by the object.
    Class[] ifaces = klass.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) { // look for interfaces implemented by the object
        rc = searchClassRenderers(ifaces[i]);
        if (rc != null)
            return rc;

    } // end for

    Class superclass = klass.getSuperclass();
    if (superclass != null) { // try the superclass now
        rc = searchClassRenderers(superclass);
        if (rc != null)
            return rc;

    } // end if

    return null; // give up

}

From source file:com.netspective.sparx.navigate.NavigationPage.java

/**
 * Try to locate the error page that can handle a given exception. First, check if we have any registered pages
 * that handle the class of the exception, then check our ancestors. If we don't handle the given exception class
 * and neither do our ancestors, check the superclass of the exception in our list and our ancestors. Keep doing
 * the check until a navigation page is found. If a page is found the navigation context's error information will
 * be appropriately set./*from   ww w.ja  v  a  2  s .co  m*/
 *
 * @param t The exception that we would like to find a error page for
 *
 * @return True if we found a page, false if no page was found
 */
public boolean findErrorPage(NavigationContext nc, Throwable t) {
    if (t instanceof ServletException) {
        ServletException se = (ServletException) t;
        Throwable rootCause = se.getRootCause();
        if (rootCause != null) {
            if (findErrorPage(nc, rootCause))
                return true;
        }
    }

    // if we're dealing with a nested exception, check to see if one of the nested exceptions is something we
    // need to handle
    if (t instanceof NestableException) {
        NestableException ne = (NestableException) t;
        Throwable[] throwables = ne.getThrowables();
        for (int i = 0; i < throwables.length; i++) {
            Throwable nestedException = throwables[i];
            if (t.getClass() == nestedException.getClass()) // don't get stuck in an infinite loop
                continue;

            if (findErrorPage(nc, nestedException))
                return true;
        }
    }

    Class exceptionClass = t.getClass();
    while (exceptionClass != null) {
        for (int i = 0; i < errorPagesList.size(); i++) {
            NavigationErrorPage errorPage = (NavigationErrorPage) errorPagesList.get(i);
            if (errorPage.canHandle(t, false) || errorPage.canHandle(exceptionClass, false)) {
                nc.setErrorPageException(errorPage, t, exceptionClass);
                return true;
            }

            // check if we can handle of the interfaces of the current exception class
            Class[] interfaces = exceptionClass.getInterfaces();
            for (int intf = 0; intf < interfaces.length; intf++) {
                Class interfaceClass = interfaces[intf];
                if (errorPage.canHandle(interfaceClass, false)) {
                    nc.setErrorPageException(errorPage, t, interfaceClass);
                    return true;
                }
            }
        }

        exceptionClass = exceptionClass.getSuperclass();
        if (!Throwable.class.isAssignableFrom(exceptionClass))
            break;
    }

    NavigationPage parentPage = (NavigationPage) getParent();
    if (parentPage != null) {
        if (parentPage.findErrorPage(nc, t))
            return true;
    }

    // if we get to here, neither we nor our ancestors know how to handle this exception so plead ignorance
    return false;
}

From source file:com.phoenixnap.oss.ramlapisync.javadoc.JavaDocExtractor.java

/**
 * Extracts the Java Doc for a specific class from its Source code as well as any superclasses or implemented
 * interfaces.// w w  w .j a  va 2  s  . c o  m
 * 
 * @param clazz The Class for which to get javadoc
 * @return A parsed documentation store with the class's Javadoc or empty if none is found.
 */
public JavaDocStore getJavaDoc(Class<?> clazz) {

    if (clazz.isArray()) {
        clazz = clazz.getComponentType();
    }
    // we need to start off from some base directory
    if (baseDir == null || clazz.isPrimitive()) {
        return new JavaDocStore();
    }

    String classPackage = clazz.getPackage() == null ? "" : clazz.getPackage().getName();
    // lets eliminate some stardard stuff
    if (classPackage.startsWith("java") || (classPackage.startsWith("org")
            && (classPackage.startsWith("org.hibernate") || classPackage.startsWith("org.raml")
                    || classPackage.startsWith("org.springframework")))) {
        return new JavaDocStore();
    }

    if (javaDocCache.containsKey(clazz)) {
        return javaDocCache.get(clazz);
    }
    logger.debug("Getting Javadoc for: " + clazz.getSimpleName());
    JavaDocStore javaDoc = new JavaDocStore();

    try {

        File file = FileSearcher.fileSearch(baseDir, clazz);

        if (file != null) {
            logger.debug("Found: " + file.getAbsolutePath());
            FileInputStream in = new FileInputStream(file);

            CompilationUnit cu;
            try {
                // parse the file
                cu = JavaParser.parse(in);
            } finally {
                in.close();
            }
            // visit and print the class docs names
            new ClassVisitor(javaDoc).visit(cu, null);
            // visit and print the methods names
            new MethodVisitor(javaDoc).visit(cu, null);
            // visit and print the field names
            new FieldVisitor(javaDoc).visit(cu, null);
        } else {
            logger.warn("*** WARNING: Missing Source for: " + clazz.getSimpleName() + ". JavaDoc Unavailable.");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    // After we complete this class, we need to check its parents and interfaces to extract as much documentation as
    // possible
    if (clazz.getInterfaces() != null && clazz.getInterfaces().length > 0) {
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            javaDoc.merge(getJavaDoc(interfaceClass));
        }
    }
    if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
        javaDoc.merge(getJavaDoc(clazz.getSuperclass()));
    }

    javaDocCache.put(clazz, javaDoc);
    return javaDoc;
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private void writeValidateInterfaces(final SourceWriter sw, final Class<?> clazz, final Stage stage,
        final PropertyDescriptor ppropertyDescription, final boolean expandDefaultGroupSequence,
        final String groupsVarName) throws UnableToCompleteException {
    for (final Class<?> type : clazz.getInterfaces()) {
        this.writeValidatorCall(sw, type, stage, ppropertyDescription, expandDefaultGroupSequence,
                groupsVarName);//from   w  w  w  .j a v  a  2 s  .co  m
        this.writeValidateInterfaces(sw, type, stage, ppropertyDescription, expandDefaultGroupSequence,
                groupsVarName);
    }
}

From source file:mesquite.lib.MesquiteModule.java

/** returns whether the passed class, or a superclass or interface of it, has the passed name*/
public static boolean nameIsInstanceOf(String n, Class c) {
    if (c == null || StringUtil.blank(n))
        return false;
    Class sup = c;//from   w  ww  .  ja  v a  2  s  . co  m
    while (sup != null) {
        if (n.equalsIgnoreCase(getShortClassName(sup)))
            return true;
        if (n.equalsIgnoreCase(sup.getName()))
            return true;
        sup = sup.getSuperclass();
    }
    //also check using  Class[] getInterfaces() to see if the class has an interface of the given name
    Class[] interfaces = c.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (interfaces[i].getName().equalsIgnoreCase(n))
            return true;
    }
    return false;

}

From source file:org.omnaest.utils.webservice.rest.RestClientFactory.java

/**
 * Factory method for new REST client proxy instances. <br>
 * <br>//from  ww  w.j a  va2  s  . c  o  m
 * This method can be used if there was no default {@link RestInterfaceMethodInvocationHandler} set at constructor time
 * 
 * @param type
 * @param baseAddress
 * @param restInterfaceMethodInvocationHandler
 *          {@link RestInterfaceMethodInvocationHandler}
 * @return
 */
@SuppressWarnings({ "unchecked" })
protected <T> T newRestClient(final Class<T> type, final URI baseAddress,
        final RestInterfaceMethodInvocationHandler restInterfaceMethodInvocationHandler) {
    Assert.isNotNull(restInterfaceMethodInvocationHandler,
            "restInterfaceMethodInvocationHandler instance must not be null");
    Assert.isNotNull(baseAddress, "baseAddress must not be null");
    Assert.isNotNull(type, "type must not be null");

    //
    T retval = null;
    if (type != null && baseAddress != null) {
        final Factory<Object> restClientfactory = new Factory<Object>() {
            @SuppressWarnings("cast")
            @Override
            public Object newInstance() {
                //
                Tuple2<StubCreator<Object>, RestInterfaceMetaInformation> cachedStubCreatorAndMetaInfo = RestClientFactory.this.stubCreatorAndRestInterfaceMetaInformationCache
                        .getOrCreate(type,
                                new Factory<Tuple2<StubCreator<Object>, RestInterfaceMetaInformation>>() {
                                    @Override
                                    public Tuple2<StubCreator<Object>, RestInterfaceMetaInformation> newInstance() {
                                        final Class<?>[] interfaces = type.getInterfaces();
                                        final RestInterfaceMetaInformation restInterfaceMetaInformation = analyzeTheRestInterfaceMetaInformation(
                                                type);
                                        return new Tuple2<StubCreator<Object>, RestInterfaceMetaInformation>(
                                                new StubCreator<Object>(type, interfaces),
                                                restInterfaceMetaInformation);
                                    }
                                });

                final RestInterfaceMetaInformation restInterfaceMetaInformation = cachedStubCreatorAndMetaInfo
                        .getValueSecond();
                final MethodInvocationHandler methodInvocationHandler = new RestClientMethodInvocationHandler(
                        restInterfaceMetaInformation, baseAddress, restInterfaceMethodInvocationHandler);

                final StubCreator<Object> stubCreator = cachedStubCreatorAndMetaInfo.getValueFirst();

                return (T) stubCreator.build(methodInvocationHandler);
            }
        };

        final boolean isCacheable = restInterfaceMethodInvocationHandler == this.restInterfaceMethodInvocationHandler;
        if (isCacheable) {
            retval = (T) this.restClientInstanceCache.getOrCreate(new TypeAndBaseAddress(type, baseAddress),
                    restClientfactory);
        } else {
            retval = (T) restClientfactory.newInstance();
        }

    }
    return retval;
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Loads the integration test classes from the class path and publishes them
 * to the OSGi registry./*from   w ww.j  a  va 2  s . c o  m*/
 * 
 * @param path
 *          the bundle path to load classes from
 * @param bundle
 *          the bundle
 */
private List<IntegrationTest> loadIntegrationTestClasses(String path, Bundle bundle) {
    List<IntegrationTest> tests = new ArrayList<IntegrationTest>();

    // Load the classes in question
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Enumeration<?> entries = bundle.findEntries("/", "*.class", true);
    if (entries == null) {
        return tests;
    }

    // Look at the classes and instantiate those that implement the integration
    // test interface.
    while (entries.hasMoreElements()) {
        URL url = (URL) entries.nextElement();
        Class<?> c = null;
        String className = url.getPath();
        try {
            className = className.substring(1, className.indexOf(".class"));
            className = className.replace('/', '.');
            c = loader.loadClass(className);
            boolean implementsInterface = Arrays.asList(c.getInterfaces()).contains(IntegrationTest.class);
            boolean extendsBaseClass = false;
            if (c.getSuperclass() != null) {
                extendsBaseClass = IntegrationTestBase.class.getName().equals(c.getSuperclass().getName());
            }
            if (!implementsInterface && !extendsBaseClass)
                continue;
            IntegrationTest test = (IntegrationTest) c.newInstance();
            test.setSite(this);
            tests.add(test);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Implementation " + className + " for integration test of class '"
                    + identifier + "' not found", e);
        } catch (NoClassDefFoundError e) {
            // We are trying to load each and every class here, so we may as well
            // see classes that are not meant to be loaded
            logger.debug("The related class " + e.getMessage() + " for potential test case implementation "
                    + className + " could not be found");
        } catch (InstantiationException e) {
            throw new IllegalStateException("Error instantiating impelementation " + className
                    + " for integration test '" + identifier + "'", e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for integration test '" + identifier + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for integration test '" + identifier + "'",
                    t);
        }

    }
    return tests;
}