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:com.strandls.alchemy.rest.client.AlchemyRestClientFactory.java

/**
 * Get an instance of a rest proxy instance for the service class.
 *
 * @param serviceClass//from w w  w . j ava2  s.  c om
 *            the service class.
 * @return the proxy implementation that invokes the remote service.
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public <T> T getInstance(@NonNull final Class<T> serviceClass) throws Exception {
    final ProxyFactory factory = new ProxyFactory();
    if (serviceClass.isInterface()) {
        factory.setInterfaces(new Class[] { serviceClass });
    } else {
        factory.setSuperclass(serviceClass);
    }
    factory.setFilter(new MethodFilter() {
        @Override
        public boolean isHandled(final Method method) {
            return Modifier.isPublic(method.getModifiers());
        }
    });

    final Class<?> klass = factory.createClass();
    final Object instance = objenesis.getInstantiatorOf(klass).newInstance();
    ((ProxyObject) instance).setHandler(new RestMethodInvocationHandler(baseUri, clientProvider,
            interfaceAnalyzer.analyze(serviceClass), responseToThrowableMapper, builderFilter));
    return (T) instance;
}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

/**
 * Collects the list of required files without content.
 * @param clazz the class that related files should be collected for. (joda style)
 * @return List of files that are required for specified class or 
 * null if none are required. //from   w  ww  .j  a v  a2  s .c o  m
 */
protected List<ClassLoaderFile> collectRequiredFiles(Class<?> clazz) {
    FileDependency fileDependency = clazz.getAnnotation(FileDependency.class);

    if (fileDependency == null)
        return null;

    List<ClassLoaderFile> files = new ArrayList<ClassLoaderFile>();

    if (fileDependency.dependencyProvider().equals(IFileDependencyProvider.class)) {// we have static files
        //         ContentType contentType = fileDependency.accessType() == FileAccess.ReadOnly ? 
        //                                    ContentType.ROFILE : ContentType.RWFILE;
        ContentType contentType = ContentType.ROFILE;

        String[] fileNames = fileDependency.files();

        if (fileNames == null || fileNames.length == 0)
            return null;

        for (String filename : fileNames) {
            File file = RemoteClassLoaderUtils.getRelativePathFile(filename);
            if (!file.exists()) {
                log.severe("Class " + clazz.getName() + " set file " + filename
                        + " as required, but the file is missing at " + file.getAbsolutePath());
                continue;
            }

            files.add(new ClassLoaderFile(filename, file.lastModified(), file.length(), contentType));
        }
    } else {// we have dynamic file list, let's process it.
        Class<? extends IFileDependencyProvider> dependentFilesProviderClass = fileDependency
                .dependencyProvider();
        if (dependentFilesProviderClass == null)
            return null;

        //checking if we can create this class
        if (dependentFilesProviderClass.isInterface()
                || Modifier.isAbstract(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is either abstract or interface.");

        if (dependentFilesProviderClass.getEnclosingClass() != null
                && !Modifier.isStatic(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is internal and not static. The class has to be static in this case.");

        Constructor<? extends IFileDependencyProvider> constructor = null;
        try {
            constructor = dependentFilesProviderClass.getDeclaredConstructor();
        } catch (NoSuchMethodException ex) {
            throw new JCloudScaleException(ex, "Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class cannot be created as it has no parameterless constructor.");
        }

        try {
            if (!constructor.isAccessible())
                constructor.setAccessible(true);

            IFileDependencyProvider provider = constructor.newInstance();

            for (DependentFile dependentFile : provider.getDependentFiles()) {
                File file = RemoteClassLoaderUtils.getRelativePathFile(dependentFile.filePath);
                if (!file.exists()) {
                    log.severe("Class " + clazz.getName() + " set file " + dependentFile.filePath
                            + " as required, but the file is missing.");
                    continue;
                }

                //               ContentType contentType = dependentFile.accessType == FileAccess.ReadOnly ? 
                //                     ContentType.ROFILE : ContentType.RWFILE;
                ContentType contentType = ContentType.ROFILE;

                files.add(new ClassLoaderFile(file.getPath(), file.lastModified(), file.length(), contentType));
            }
        } catch (Exception ex) {
            log.severe("Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                    + clazz.getName() + " threw exception during execution:" + ex.toString());
            throw new JCloudScaleException(ex,
                    "Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                            + clazz.getName() + " threw exception during execution.");
        }
    }

    return files;
}

From source file:io.konik.utils.RandomInvoiceGenerator.java

public Object populteData(Class<?> root, String name) throws InstantiationException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    Object rootObj;// w  w w  .j  a v  a  2  s .c  o  m
    if (isLeafType(root)) {//final type
        return generatePrimitveValue(root, name);
    }
    rootObj = createNewInstance(root);

    // get method and populate each of them
    Method[] methods = root.getMethods();
    for (Method method : methods) {
        int methodModifiers = method.getModifiers();
        Class<?> methodParameter = null;
        if (Modifier.isAbstract(methodModifiers) || method.isSynthetic())
            continue;
        if (method.getName().startsWith("add")) {
            methodParameter = method.getParameterTypes()[0];
            if (methodParameter != null && !methodParameter.isArray()
                    && (methodParameter.isInterface() || Modifier.isAbstract(methodParameter.getModifiers()))) {
                continue;
            }
        }
        //getter
        else if (method.getName().startsWith("get")
                && !Collection.class.isAssignableFrom(method.getReturnType())
                && !method.getName().equals("getClass") && !Modifier.isAbstract(methodModifiers)) {
            methodParameter = method.getReturnType();
        } else {
            continue;// next on setter
        }
        if (methodParameter == null || methodParameter.isInterface()) {
            continue;
        }
        Object popultedData = populteData(methodParameter, method.getName());
        setValue(rootObj, method, popultedData);
    }
    return rootObj;
}

From source file:net.firejack.platform.core.utils.Factory.java

private <T> T convertFrom0(Class<?> clazz, Object dto) {
    if (dto == null)
        return null;
    Object bean = null;//from   w w w  . ja va2s  . c o  m
    try {
        bean = clazz.newInstance();
        List<FieldInfo> infos = fields.get(dto.getClass());
        if (infos == null) {
            infos = getAllField(dto.getClass(), dto.getClass(), new ArrayList<FieldInfo>());
            fields.put(dto.getClass(), infos);
        }
        for (FieldInfo info : infos) {
            if (info.readonly()) {
                continue;
            }

            String name = info.name();
            Object entity = bean;
            clazz = entity.getClass();
            String[] lookup = name.split("\\.");

            if (lookup.length > 1) {
                if (isNullValue(dto, info.getField().getName()))
                    continue;

                for (int i = 0; i < lookup.length - 1; i++) {
                    Object instance = get(entity, lookup[i], null);
                    if (instance == null) {
                        FieldInfo fieldInfo = getField(clazz, lookup[i]);
                        Class<?> type = fieldInfo.getType();
                        if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) {
                            instance = type.newInstance();
                            set(entity, lookup[i], instance);

                            entity = instance;
                            clazz = type;
                        }
                    } else {
                        entity = instance;
                        clazz = instance.getClass();
                    }
                }
                name = lookup[lookup.length - 1];
            }

            FieldInfo distField = getField(clazz, name);
            if (distField != null) {
                Class<?> type = distField.getType();
                Object value = get(dto, info.getField().getName(), type);
                if (value != null) {
                    if (value instanceof AbstractDTO) {
                        if (contains(value)) {
                            Object convert = get(value);
                            set(entity, name, convert);
                        } else {
                            add(value, null);
                            Object convert = convertFrom0(type, value);
                            add(value, convert);
                            set(entity, name, convert);
                        }
                    } else if (value instanceof Collection) {
                        Collection result = (Collection) value;
                        Class<?> arrayType = distField.getGenericType();
                        if (AbstractModel.class.isAssignableFrom(arrayType)
                                || arrayType.isAnnotationPresent(XmlAccessorType.class)) {
                            try {
                                result = (Collection) value.getClass().newInstance();
                            } catch (InstantiationException e) {
                                result = new ArrayList();
                            }

                            for (Object o : (Collection) value) {
                                Object convert = convertFrom0(arrayType, o);
                                result.add(convert);
                            }
                        }
                        set(entity, name, result);
                    } else {
                        set(entity, name, value);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }
    return (T) bean;
}

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

protected void checkInterfaceAndMethods(Class<?> interfaceClass, List<MethodConfig> methods) {
    if (interfaceClass == null) {
        throw new IllegalStateException("interface not allow null!");
    }//from   ww  w  .  j  a  va 2s.c o m
    if (!interfaceClass.isInterface()) {
        throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
    }
    // ??
    if (methods != null && !methods.isEmpty()) {
        for (MethodConfig methodBean : methods) {
            String methodName = methodBean.getName();
            if (methodName == null || methodName.length() == 0) {
                throw new IllegalStateException(
                        "<motan:method> name attribute is required! Please check: <motan:service interface=\""
                                + interfaceClass.getName()
                                + "\" ... ><motan:method name=\"\" ... /></<motan:referer>");
            }
            java.lang.reflect.Method hasMethod = null;
            for (java.lang.reflect.Method method : interfaceClass.getMethods()) {
                if (method.getName().equals(methodName)) {
                    if (methodBean.getArgumentTypes() != null
                            && ReflectUtil.getMethodParamDesc(method).equals(methodBean.getArgumentTypes())) {
                        hasMethod = method;
                        break;
                    }
                    if (methodBean.getArgumentTypes() != null) {
                        continue;
                    }
                    if (hasMethod != null) {
                        throw new MotanFrameworkException(
                                "The interface " + interfaceClass.getName() + " has more than one method "
                                        + methodName + " , must set argumentTypes attribute.",
                                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
                    }
                    hasMethod = method;
                }
            }
            if (hasMethod == null) {
                throw new MotanFrameworkException(
                        "The interface " + interfaceClass.getName() + " not found method " + methodName,
                        MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
            }
            methodBean.setArgumentTypes(ReflectUtil.getMethodParamDesc(hasMethod));
        }
    }
}

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

private ContributionDef createContributionToMasterObjectProvider() {

    return new AbstractContributionDef() {
        @Override/*from ww w.  j  av  a  2s .c om*/
        public String getServiceId() {
            return "MasterObjectProvider";
        }

        @Override
        public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
                OrderedConfiguration configuration) {
            final OperationTracker tracker = resources.getTracker();

            final ApplicationContext context = resources.getService(SERVICE_ID, ApplicationContext.class);

            //region CUSTOMIZATION
            final ObjectProvider springBeanProvider = new ObjectProvider() {
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {

                    try {
                        T bean = context.getBean(objectType);
                        if (!objectType.isInterface()) {
                            return bean;
                        }
                        // We proxify here because Tapestry calls toString method on proxy, which realizes the underlying service, with scope issues
                        return (T) Proxy.newProxyInstance(objectType.getClassLoader(),
                                new Class<?>[] { objectType }, new AbstractInvocationHandler() {
                                    @Override
                                    protected Object handleInvocation(Object proxy, Method method,
                                            Object[] args) throws Throwable {
                                        String methodName = method.getName();
                                        if (methodName.equals("equals")) {
                                            // Only consider equal when proxies are identical.
                                            return (proxy == args[0]);
                                        }
                                        if (methodName.equals("hashCode")) {
                                            // Use hashCode of proxy.
                                            return System.identityHashCode(proxy);
                                        }
                                        if (methodName.equals("toString")) {
                                            return "Current Spring " + objectType.getSimpleName();
                                        }
                                        try {
                                            return method.invoke(bean, args);
                                        } catch (InvocationTargetException e) {
                                            throw e.getCause();
                                        }
                                    }
                                });

                    } catch (NoUniqueBeanDefinitionException e) {
                        String message = String.format(
                                "Spring context contains %d beans assignable to type %s.",
                                e.getNumberOfBeansFound(), PlasticUtils.toTypeName(objectType));

                        throw new IllegalArgumentException(message, e);
                    } catch (NoSuchBeanDefinitionException e) {
                        return null;
                    }
                }
            };
            //endregion

            final ObjectProvider springBeanProviderInvoker = new ObjectProvider() {
                @Override
                public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
                        final ObjectLocator locator) {
                    return tracker.invoke("Resolving dependency by searching Spring ApplicationContext",
                            () -> springBeanProvider.provide(objectType, annotationProvider, locator));
                }
            };

            ObjectProvider outerCheck = new ObjectProvider() {
                @Override
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {
                    // I think the following line is the only reason we put the
                    // SpringBeanProvider here,
                    // rather than in SpringModule.

                    if (!applicationContextCreated.get())
                        return null;

                    return springBeanProviderInvoker.provide(objectType, annotationProvider, locator);
                }
            };

            configuration.add("SpringBean", outerCheck, "after:AnnotationBasedContributions",
                    "after:ServiceOverride");
        }
    };
}

From source file:necauqua.mods.cm.asm.ASM.java

public static byte[] doTransform(String className, byte[] original) {
    ClassPatcher patcher = patchers.get(className);
    if (patcher != null) {
        Log.debug("Patching class: " + className);
        ClassReader reader = new ClassReader(original);
        ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES) {

            @Override/*w ww. j a  va  2  s  .c om*/
            protected String getCommonSuperClass(String type1, String type2) { // HAX defined
                Class<?> c, d;
                ClassLoader classLoader = ChiseledMe.class.getClassLoader(); // this one line was breaking stuff :/ fixed
                try {
                    c = Class.forName(type1.replace('/', '.'), false, classLoader);
                    d = Class.forName(type2.replace('/', '.'), false, classLoader);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.toString());
                }
                if (c.isAssignableFrom(d)) {
                    return type1;
                }
                if (d.isAssignableFrom(c)) {
                    return type2;
                }
                if (c.isInterface() || d.isInterface()) {
                    return "java/lang/Object";
                } else {
                    do {
                        c = c.getSuperclass();
                    } while (!c.isAssignableFrom(d));
                    return c.getName().replace('.', '/');
                }
            }
        };
        ClassPatchVisitor visitor = new ClassPatchVisitor(writer, patcher);
        try {
            reader.accept(visitor, ClassReader.SKIP_FRAMES);
        } catch (Exception e) {
            Log.error("Couldn't accept patch visitor!", e);
        }

        String cls = className.substring(className.lastIndexOf('.') + 1);
        String stuff;
        stuff = visitor.unusedPatches.stream().filter(patch -> {
            if (patch.optional) {
                Log.debug("One of patches from " + cls
                        + " wasn't applied but ignoring because it's marked as optional (eg. @SideOnly)");
                return false;
            } else {
                return true;
            }
        }).map(p -> cls + "." + p.getMethodNames()).collect(Collectors.joining("\n    ", "\n    ", ""));
        if (!stuff.equals("\n    ")) {
            Log.error("\n*** Those methods were not found:" + stuff);
            throw new IllegalStateException("Coremod failed!");
        }
        stuff = visitor.modifiers.asMap().entrySet().stream()
                .flatMap(entry -> entry.getValue().stream()
                        .filter(mod -> mod.code == null || !mod.code.succededOnce())
                        .map(mod -> mod + " from " + cls + "." + entry.getKey()))
                .collect(Collectors.joining("\n    ", "\n    ", ""));
        if (!stuff.equals("\n    ")) {
            Log.error("\n*** Those modifiers were not applied:" + stuff);
            throw new IllegalStateException("Coremod failed!");
        }
        try {
            return writer.toByteArray();
        } catch (Exception e) {
            Log.error("Couldn't write patched class!", e);
            return original;
        }
    }
    return original;
}

From source file:org.geoserver.jdbcconfig.internal.DbMappings.java

public Map<String, PropertyType> getPropertyTypes(final Class<?> queryType) {
    checkArgument(queryType.isInterface(), "queryType should be an interface");
    final Integer typeId = getTypeId(queryType);
    Map<String, PropertyType> propTypes = this.propertyTypes.get(typeId);
    return propTypes;
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Create a bean element for the given class.
 *
 * @param clazz the target class//from   ww  w  .ja va 2  s  . c o  m
 * @return the bean element or a list of beans for each service provider
 * available
 */
public List<?> createElement(Class<?> clazz) {
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        return createServiceProviderElements(clazz);
    }
    if (clazz.getConstructors().length == 0) {
        log.warn("Class {} has no public no-argument constructor!", clazz);
        return Collections.emptyList();
    }
    Object obj;
    try {
        obj = clazz.newInstance();
        //build a "bean" element for each class
        buildBeanElement(obj);
        return Arrays.asList(obj);
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Collections.emptyList();
}

From source file:edu.isi.karma.rdf.OfflineRdfGenerator.java

private KR2RMLRDFWriter createBloomFilterWriter(PrintWriter bloomfilterpw, Boolean isRDF, String baseURI)
        throws Exception {

    Reflections reflections = new Reflections("edu.isi.karma.kr2rml.writer");

    Set<Class<? extends KR2RMLRDFWriter>> subTypes = reflections.getSubTypesOf(KR2RMLRDFWriter.class);

    for (Class<? extends KR2RMLRDFWriter> subType : subTypes) {
        if (!Modifier.isAbstract(subType.getModifiers()) && !subType.isInterface()
                && subType.getName().equals("BloomFilterKR2RMLRDFWriter"))
            try {
                KR2RMLRDFWriter writer = subType.newInstance();
                writer.setWriter(bloomfilterpw);
                Properties p = new Properties();
                p.setProperty("is.rdf", isRDF.toString());
                p.setProperty("base.uri", baseURI);
                writer.initialize(p);/*from   w  w  w .j  a  v a  2  s  .co m*/
                return writer;
            } catch (Exception e) {
                bloomfilterpw.close();
                throw new Exception("Unable to instantiate bloom filter writer", e);
            }
    }

    bloomfilterpw.close();
    throw new Exception("Bloom filter writing support not enabled.  Please recompile with -Pbloom");
}