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.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(List<ParameterTree> parameterTrees, Class<?> type, Type genericType) throws Exception {
    Object result = null;//w  ww . jav  a2  s . c o  m

    if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterTrees.size());

        int index = 0;
        for (ParameterTree parameterTree : parameterTrees) {
            Object objectConverted = convert(parameterTree, componentType, null);
            tabConverted[index] = objectConverted;
            index++;
        }

        result = tabConverted;

    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        for (ParameterTree parameterTree : parameterTrees) {
            Object converted = convert(parameterTree, convertType, null);
            instance.add(converted);
        }

        result = instance;
    }

    return result;
}

From source file:com.link_intersystems.lang.reflect.Class2.java

/**
 *
 * @param <TI>/* w ww .  j a  va 2  s.  c o m*/
 *            the expected type so that clients must not cast.
 * @param typeVariable
 *            the type variable that defines the class to be instantiated.
 * @param constructorArgs
 *            the arguments to use when constructing the bound type.
 * @return an instance of the bound type defined by the typeVariable -
 *         constructing it with the constructorArgs. The right constructor
 *         is determined by the constructorArgs object's types.
 * @throws IllegalStateException
 *             in case of an {@link InstantiationException},
 *             {@link IllegalAccessException} or
 *             {@link InvocationTargetException} that arises when trying to
 *             instantiate the class bound to the type variable.
 * @throws IllegalArgumentException
 *             if the type bound to the type variable is an interface or the
 *             constructor that is called to instantiate the class bound to
 *             the type variable itself throws an
 *             {@link IllegalArgumentException} or. The original exception
 *             is wrapped to provide more information.
 */
public <TI> TI getBoundInstance(TypeVariable<?> typeVariable, Object... constructorArgs) {
    Class<TI> typeClass = getBoundClass(typeVariable);
    if (typeClass.isInterface()) {
        throw new IllegalArgumentException(
                "The type variable's (" + typeVariable + ") bound type (" + typeClass + ") is an interface.");
    }
    Class2<TI> class2 = Class2.get(typeClass);
    Class<?>[] constructorArgClasses = new Class<?>[constructorArgs.length];
    for (int i = 0; i < constructorArgs.length; i++) {
        Object arg = constructorArgs[i];
        if (arg != null) {
            constructorArgClasses[i] = arg.getClass();
        }
    }

    Constructor2<?> constructor2 = class2.getApplicableConstructor(constructorArgClasses);
    if (constructor2 == null) {
        throw new IllegalArgumentException("Type variable's (" + typeVariable + ") bound type " + typeClass
                + " doesn't have a constructor applicable for the argument types "
                + Arrays.asList(constructorArgClasses));
    }
    try {
        @SuppressWarnings("unchecked")
        TI t = (TI) constructor2.getInvokable().invoke(constructorArgs);
        return t;
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unable to instantiate an object of " + typeClass + " using constructor "
                        + constructor2.getMember() + " with arguments " + Arrays.asList(constructorArgs),
                e);
    }
}

From source file:com.gh.bmd.jrt.android.v4.core.DefaultObjectContextRoutineBuilder.java

@Nonnull
public <TYPE> TYPE buildProxy(@Nonnull final Class<TYPE> itf) {

    if (!itf.isInterface()) {

        throw new IllegalArgumentException(
                "the specified class is not an interface: " + itf.getCanonicalName());
    }/*from  w w  w .j  a  v a 2  s.  c  o m*/

    final RoutineConfiguration configuration = mConfiguration;

    if (configuration != null) {

        warn(configuration);
    }

    final Object proxy = Proxy.newProxyInstance(itf.getClassLoader(), new Class[] { itf },
            new ProxyInvocationHandler(this, itf));
    return itf.cast(proxy);
}

From source file:io.swagger.jaxrs.SynapseReader.java

private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource,
        Set<String> parentConsumes, Set<String> parentProduces, Map<String, Tag> parentTags,
        List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
    Api api = (Api) cls.getAnnotation(Api.class);
    boolean isServiceAnnotated = (cls.getAnnotation(Service.class) != null);
    boolean isMarkedService = SynapseEndpointServiceMarker.class.isAssignableFrom(cls) && !cls.isInterface();

    Map<String, Tag> tags = new HashMap<>();
    List<SecurityRequirement> securities = new ArrayList<>();

    final List<String> consumes = new ArrayList<>();
    final List<String> produces = new ArrayList<>();
    final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);

    /*/*from   ww  w  .j ava2  s. co m*/
     *   Only read @Api configuration if:
     *
     *   @Api annotated AND
     *   @Path annotated AND
     *   @Api (hidden) false
     *   isSubresource false
     *
     *   OR
     *
     *   @Api annotated AND
     *   isSubresource true
     *   @Api (hidden) false
     *
     */
    final boolean readable = ((api != null && (isServiceAnnotated || isMarkedService) && !api.hidden()
            && !isSubresource) || (api != null && !api.hidden() && isSubresource)
            || (api != null && !api.hidden() && getConfig().isScanAllResources()));

    if (readable) {
        // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
        Set<String> tagStrings = extractTags(api);
        tagStrings.stream().forEach((tagString) -> {
            Tag tag = new Tag().name(tagString);
            tags.put(tagString, tag);
        });
        tags.keySet().stream().forEach((tagName) -> {
            getSwagger().tag(tags.get(tagName));
        });

        if (api != null && !api.produces().isEmpty()) {
            produces.add(api.produces());
            //            } else if (cls.getAnnotation(Produces.class) != null) {
            //                produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
        }
        if (api != null && !api.consumes().isEmpty()) {
            consumes.add(api.consumes());
            //            } else if (cls.getAnnotation(Consumes.class) != null) {
            //                consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
        }
        if (api != null) {
            globalSchemes.addAll(parseSchemes(api.protocols()));
        }
        Authorization[] authorizations = api != null ? api.authorizations() : new Authorization[] {};

        for (Authorization auth : authorizations) {
            if (auth.value() != null && !"".equals(auth.value())) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                AuthorizationScope[] scopes = auth.scopes();
                for (AuthorizationScope scope : scopes) {
                    if (scope.scope() != null && !"".equals(scope.scope())) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
    }

    if (isSubresource) {
        if (parentTags != null) {
            tags.putAll(parentTags);
        }
    }

    if (readable || (api == null && getConfig().isScanAllResources())) {
        // merge consumes, produces

        // look for method-level annotated properties
        // handle sub-resources by looking at return type
        final List<Parameter> globalParameters = new ArrayList<>();

        // look for constructor-level annotated properties
        globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, getSwagger()));

        // look for field-level annotated properties
        globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, getSwagger()));

        // parse the method
        final Service serviceAnnotation = ReflectionUtils.getAnnotation(cls, Service.class);

        for (Method method : cls.getMethods()) {
            if (ReflectionUtils.isOverriddenMethod(method, cls)) {
                //is this a method overriden by one in a subclass?
                continue;
            }

            final RequestMapping requestMappingAnnotation = isServiceAnnotated
                    ? ReflectionUtils.getAnnotation(method, RequestMapping.class)
                    : null;
            final List<String> operationPaths = isServiceAnnotated
                    ? getPaths(serviceAnnotation, method, parentPath)
                    : isMarkedService ? getPaths(method) : null;

            Map<String, String> regexMap = new HashMap<>();

            if (operationPaths == null) {
                continue;
            }

            operationPaths.stream().map(op -> PathUtils.parsePath(op, regexMap))
                    .filter(op -> op != null && !MethodProcessor.isIgnored(op, getConfig())).forEach(op -> {
                        final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method,
                                ApiOperation.class);
                        List<String> httpMethods = extractOperationMethods(apiOperation, method,
                                SwaggerExtensions.chain());
                        if (httpMethods != null && !httpMethods.isEmpty()) {
                            httpMethods.forEach(hm -> {
                                Operation operation = null;
                                if (apiOperation != null || getConfig().isScanAllResources() || (hm != null)
                                        || requestMappingAnnotation != null || isMarkedService) {
                                    operation = MethodProcessor.parseMethod(cls, method, globalParameters,
                                            getSwagger());
                                }
                                if (operation != null) {

                                    if (parentParameters != null && !parentParameters.isEmpty()) {
                                        //add parent parameters to this Operation
                                        for (Parameter param : parentParameters) {
                                            operation.parameter(param);
                                        }
                                    }
                                    prepareOperation(operation, apiOperation, regexMap, globalSchemes);

                                    Set<String> apiConsumes = new HashSet<>(consumes);
                                    if (parentConsumes != null) {
                                        apiConsumes.addAll(parentConsumes);
                                        if (operation.getConsumes() != null) {
                                            apiConsumes.addAll(operation.getConsumes());
                                        }
                                    }

                                    Set<String> apiProduces = new HashSet<>(produces);
                                    if (parentProduces != null) {
                                        apiProduces.addAll(parentProduces);
                                        if (operation.getProduces() != null) {
                                            apiProduces.addAll(operation.getProduces());
                                        }
                                    }

                                    final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(
                                            method);
                                    if (subResource != null && !scannedResources.contains(subResource)) {
                                        scannedResources.add(subResource);
                                        read(subResource, op, hm, true, apiConsumes, apiProduces, tags,
                                                operation.getParameters(), scannedResources);

                                        // remove the sub resource so that it can visit it later in another path
                                        // but we have a room for optimization in the future to reuse the scanned result
                                        // by caching the scanned resources in the reader instance to avoid actual scanning
                                        // the the resources again
                                        scannedResources.remove(subResource);
                                    }

                                    if (apiOperation != null) {
                                        boolean hasExplicitTag = false;
                                        for (String tag : apiOperation.tags()) {
                                            if (!"".equals(tag)) {
                                                operation.tag(tag);
                                                getSwagger().tag(new Tag().name(tag));
                                            }
                                        }

                                        operation.getVendorExtensions().putAll(
                                                BaseReaderUtils.parseExtensions(apiOperation.extensions()));
                                    }

                                    if (operation.getConsumes() == null) {
                                        for (String mediaType : apiConsumes) {
                                            operation.consumes(mediaType);
                                        }
                                    }
                                    if (operation.getProduces() == null) {
                                        for (String mediaType : apiProduces) {
                                            operation.produces(mediaType);
                                        }
                                    }

                                    if (operation.getTags() == null) {
                                        for (String tagString : tags.keySet()) {
                                            operation.tag(tagString);
                                        }
                                    }
                                    // Only add global @Api securities if operation doesn't already have more specific securities
                                    if (operation.getSecurity() == null) {
                                        for (SecurityRequirement security : securities) {
                                            operation.security(security);
                                        }
                                    }

                                    Path path = getSwagger().getPath(op);
                                    if (path == null) {
                                        path = new Path();
                                        getSwagger().path(op, path);
                                    }
                                    path.set(hm, operation);

                                    readImplicitParameters(method, operation);
                                }
                            });
                        }

                    });
        }
    }

    return getSwagger();
}

From source file:org.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override//from ww w .j  a  v a 2s  .c o  m
public Object handle(Selector targetSelector, Object previousResult)
        throws InvocationTargetException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, NoSuchMethodException {

    if (!ReflectUtils.isCast(CoreInstantiationSelector.class, targetSelector)) {
        if (log.isFatalEnabled()) {
            log.fatal("Target selector can not be casted to '" + CoreInstantiationSelector.class.toString()
                    + "'");
        }
        throw new IllegalPropertyException(
                "Target selector can not be casted to '" + CoreInstantiationSelector.class.toString() + "'");
    }
    Object result = null;
    Definition definition = targetSelector.getDefinition();
    Class<?> targetClass = targetSelector.getTargetClass();
    CoreInstantiationSelector selector = (CoreInstantiationSelector) targetSelector;
    boolean runtimeLoading = definition != null && definition.isAnnotationPresent(AlwaysReload.class)
            ? definition.getAnnotation(AlwaysReload.class).value()
            : false;
    // create bean instance
    if (targetSelector instanceof InstantiationSelectorImpl) {
        InstantiationSelector instSelector = (InstantiationSelector) targetSelector;
        // nu bean  c khi to 1 phn trc 
        if (previousResult != null && (targetClass.isAnnotation() || targetClass.isInterface())) {
            throw new InterceptionException(
                    "Bean instantiation is not supported or completed if target class is "
                            + "annotation or interface and if at least one 'instantiation' interceptor "
                            + "has instantiated the corresponding 'object bean'");
        } else {
            Map<Method, MethodAspectPair> methodAspectList = new HashMap<Method, MethodAspectPair>();
            Map<Interceptor, Matcher<Definition>> map = instSelector.getMapMatcherInterceptor();
            final List<Method> methodList = new ArrayList<Method>();
            final Field[] fieldList = ReflectUtils.getDeclaredFields(targetClass, false, true);
            Enhancer.getMethods(targetClass, null, methodList);
            boolean invocationINOUT = false;
            ElementAspectFactory elementAspectFactory = new ElementAspectFactory();
            /*
             * perform method interceptor
             */
            MethodInterceptor[] methodIcptLst = instSelector.getMethodInterceptors();
            for (Method method : methodList) {
                invocationINOUT = invocationINOUT == false ? InterceptorUtils.isInvocation(definition, method)
                        : invocationINOUT;
                // creates Aspect Pair
                MethodAspectPair aspectPair = elementAspectFactory.analysesMethod(methodIcptLst, map,
                        definition, method);
                // performs advice
                executesAdvice(definition, method, provider, runtimeLoading, aspectPair);
                if (aspectPair.hasInterceptors())
                    methodAspectList.put(method, aspectPair);
            }
            /*
             * perform field interceptor
             */
            FieldInterceptor[] fieldIcpLst = instSelector.getFieldInterceptors();
            if (!targetClass.isAnnotation()) {
                for (Field field : fieldList) {
                    invocationINOUT = invocationINOUT == false
                            ? InterceptorUtils.isInvocation(definition, field)
                            : invocationINOUT;
                    // creates Aspect Pair
                    FieldAspectPair fieldAspectPair = elementAspectFactory.analysesField(fieldIcpLst, map,
                            definition, field);
                    if (fieldAspectPair.hasInterceptors()) {
                        Method setter = Utils.getDefaultSetter(targetClass, field.getName());
                        Method getter = Utils.getDefaultGetter(targetClass, field.getName());
                        if (getter == null || setter == null) {
                            throw new InterceptionException(
                                    "Does not found setter or getter of field '" + field.getName() + "'");
                        }
                        MethodInterceptor interceptor = InterceptorUtils
                                .createsFieldStackMethodInterceptor(field);
                        if (methodAspectList.containsKey(setter))
                            methodAspectList.get(setter).add(interceptor);
                        else
                            methodAspectList.put(setter, new MethodAspectPair(setter, interceptor));
                        if (methodAspectList.containsKey(getter))
                            methodAspectList.get(getter).add(interceptor);
                        else
                            methodAspectList.put(getter, new MethodAspectPair(getter, interceptor));
                    }
                }
            }
            /*
             * perform invocation in/out or annotation attributes injection
             */
            executesInOut(targetClass, definition, provider, runtimeLoading, methodAspectList, invocationINOUT);
            // Creates callbacks.
            Callback[] callbacks = new Callback[methodList.size() + 1];
            Class<? extends Callback>[] callbackTypes = new Class[methodList.size() + 1];
            for (int i = 0; i < methodList.size(); i++) {
                MethodAspectPair pair = methodAspectList.get(methodList.get(i));
                if (pair == null) {
                    callbacks[i] = NoOp.INSTANCE;
                    callbackTypes[i] = NoOp.class;
                } else {
                    callbacks[i] = new MethodInterceptorStackCallback(pair.getMethod(), previousResult,
                            pair.interceptors.toArray(new MethodInterceptor[pair.interceptors.size()]));
                    callbackTypes[i] = net.sf.cglib.proxy.MethodInterceptor.class;
                }
            }
            callbacks[methodList.size()] = new ReturnScopeNameMethodInterceptor(selector.getScopeName());
            callbackTypes[methodList.size()] = net.sf.cglib.proxy.MethodInterceptor.class;
            // Nu khng tm thy bt k ch nh khi to interceptor no
            // ==> t ng return null.
            if (methodAspectList.size() == 0 && (targetClass.isInterface())) {
                return NullClass.class;
            }
            // Create the proxied class.
            final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
            Enhancer enhancer = new Enhancer();
            if (targetClass.isAnnotation() || targetClass.isInterface())
                enhancer.setInterfaces(new Class<?>[] { targetClass, ReturnScopeName.class });
            else {
                enhancer.setSuperclass(targetClass);
                enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
            }
            enhancer.setCallbackFilter(new CallbackFilter() {
                public int accept(Method method) {

                    if (method.equals(returnScopeNameMethod))
                        return methodList.size();
                    return methodList.indexOf(method);
                }
            });
            enhancer.setCallbackTypes(callbackTypes);
            enhancer.setUseFactory(false);
            enhancer.setUseCache(true);
            enhancer.setNamingPolicy(new JGentleNamingPolicy());
            Class<?> proxied = enhancer.createClass();
            Enhancer.registerStaticCallbacks(proxied, callbacks);
            MetaDefObject metaObj = new MetaDefObject();
            findInOutNonRuntime(metaObj, definition);
            CachedConstructor cons = Utils.createConstructionProxy(definition, proxied,
                    instSelector.getArgTypes(), metaObj);
            selector.getCachingList().put(definition, cons);
            result = cons.newInstance(instSelector.getArgs());
            // executes process after bean is created
            prepareSingletonBean(selector, provider, result);
            CommonFactory.singleton().executeProcessAfterBeanCreated(targetClass, metaObj, provider, result,
                    definition);
        }
    } else if (targetSelector instanceof CoreInstantiationSelectorImpl
            && !(targetSelector instanceof InstantiationSelectorImpl)) {
        result = createPureBeanInstance(targetSelector, targetClass, definition, provider, runtimeLoading);
    }
    return result;
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedProxyClassGenerator.java

/**
 * Generates an implementation of the given managed type.
 * <p>//w  w  w .  ja v  a2  s. c o  m
 * The generated class will implement/extend the managed type and will:
 * <ul>
 *     <li>provide implementations for abstract getters and setters that delegate to model nodes</li>
 *     <li>provide a `toString()` implementation</li>
 *     <li>mix-in implementation of {@link ManagedInstance}</li>
 *     <li>provide a constructor that accepts a {@link ModelElementState}, which will be used to implement the above.</li>
 * </ul>
 *
 * In case a delegate schema is supplied, the generated class will also have:
 * <ul>
 *     <li>a constructor that also takes a delegate instance</li>
 *     <li>methods that call through to the delegate instance</li>
 * </ul>
 */
public <T, M extends T, D extends T> Class<? extends M> generate(ModelStructSchema<M> managedSchema,
        ModelStructSchema<D> delegateSchema) {
    if (delegateSchema != null
            && Modifier.isAbstract(delegateSchema.getType().getConcreteClass().getModifiers())) {
        throw new IllegalArgumentException("Delegate type must be null or a non-abstract type");
    }
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);

    ModelType<M> managedType = managedSchema.getType();

    StringBuilder generatedTypeNameBuilder = new StringBuilder(managedType.getName());
    if (delegateSchema != null) {
        generatedTypeNameBuilder.append("$BackedBy_")
                .append(delegateSchema.getType().getName().replaceAll("\\.", "_"));
    } else {
        generatedTypeNameBuilder.append("$Impl");
    }

    String generatedTypeName = generatedTypeNameBuilder.toString();
    Type generatedType = Type.getType("L" + generatedTypeName.replaceAll("\\.", "/") + ";");

    Class<M> managedTypeClass = managedType.getConcreteClass();
    Class<?> superclass;
    final ImmutableSet.Builder<String> interfaceInternalNames = ImmutableSet.builder();
    final ImmutableSet.Builder<Class<?>> typesToDelegate = ImmutableSet.builder();
    typesToDelegate.add(managedTypeClass);
    interfaceInternalNames.add(MANAGED_INSTANCE_TYPE);
    if (managedTypeClass.isInterface()) {
        superclass = Object.class;
        interfaceInternalNames.add(Type.getInternalName(managedTypeClass));
    } else {
        superclass = managedTypeClass;
    }
    // TODO:LPTR This should be removed once BinaryContainer is a ModelMap
    // We need to also implement all the interfaces of the delegate type because otherwise
    // BinaryContainer won't recognize managed binaries as BinarySpecInternal
    if (delegateSchema != null) {
        ModelSchemaUtils.walkTypeHierarchy(delegateSchema.getType().getConcreteClass(),
                new ModelSchemaUtils.TypeVisitor<D>() {
                    @Override
                    public void visitType(Class<? super D> type) {
                        if (type.isInterface()) {
                            typesToDelegate.add(type);
                            interfaceInternalNames.add(Type.getInternalName(type));
                        }
                    }
                });
    }

    generateProxyClass(visitor, managedSchema, delegateSchema, interfaceInternalNames.build(),
            typesToDelegate.build(), generatedType, Type.getType(superclass));

    return defineClass(visitor, managedTypeClass.getClassLoader(), generatedTypeName);
}

From source file:com.zenesis.qx.remote.ProxyTypeImpl.java

/**
 * Constructor, used for defining interfaces which are to be proxied
 * @param className//  w w w .  j  av  a 2  s. co m
 * @param methods
 */
public ProxyTypeImpl(ProxyType superType, Class clazz, Set<ProxyType> interfaces) {
    super();
    if (interfaces == null)
        interfaces = Collections.EMPTY_SET;
    this.superType = superType;
    this.interfaces = interfaces;
    this.clazz = clazz;

    MethodsCompiler methodsCompiler = new MethodsCompiler();

    // Get a complete list of methods from the interfaces that the new class has to 
    //   implement; we include methods marked as DoNotProxy so that we can check for 
    //   conflicting instructions
    if (!clazz.isInterface()) {
        // Get a full list of the interfaces which our class has to implement
        HashSet<ProxyType> allInterfaces = new HashSet<ProxyType>();
        getAllInterfaces(allInterfaces, interfaces);

        for (ProxyType ifcType : allInterfaces) {
            try {
                methodsCompiler.addMethods(Class.forName(ifcType.getClassName()), true);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Cannot find class " + ifcType.getClassName());
            }
        }
    }

    boolean defaultProxy = false;
    if (clazz.isInterface())
        defaultProxy = true;
    else {
        for (Class tmp = clazz; tmp != null; tmp = tmp.getSuperclass()) {
            if (factoryMethod == null) {
                for (Method method : tmp.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(FactoryMethod.class)) {
                        if (!Modifier.isStatic(method.getModifiers()))
                            throw new IllegalStateException("Cannot use method " + method
                                    + " as FactoryMethod because it is not static");
                        factoryMethod = method;
                        method.setAccessible(true);
                        break;
                    }
                }
            }
            if (tmp.isAnnotationPresent(AlwaysProxy.class)) {
                defaultProxy = true;
                break;
            } else if (tmp.isAnnotationPresent(ExplicitProxyOnly.class)) {
                break;
            }
        }
    }

    // If the class does not have any proxied interfaces or the class is marked with
    //   the AlwaysProxy annotation, then we take methods from the class definition
    methodsCompiler.addMethods(clazz, defaultProxy);

    methodsCompiler.checkValid();
    methodsCompiler.removeSuperTypeMethods();

    // Load properties
    HashMap<String, ProxyEvent> events = new HashMap<String, ProxyEvent>();
    HashMap<String, ProxyProperty> properties = new HashMap<String, ProxyProperty>();
    Properties annoProperties = (Properties) clazz.getAnnotation(Properties.class);
    if (annoProperties != null) {
        for (Property anno : annoProperties.value()) {
            ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }
    for (Field field : clazz.getDeclaredFields()) {
        Property anno = field.getAnnotation(Property.class);
        if (anno != null) {
            ProxyProperty property = new ProxyPropertyImpl(clazz,
                    anno.value().length() > 0 ? anno.value() : field.getName(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }

    for (Method method : clazz.getDeclaredMethods()) {
        String name = method.getName();
        if (name.length() < 4 || !name.startsWith("get") || !Character.isUpperCase(name.charAt(3)))
            continue;
        Property anno = method.getAnnotation(Property.class);
        if (anno == null)
            continue;

        name = Character.toLowerCase(name.charAt(3)) + name.substring(4);
        if (properties.containsKey(name))
            continue;

        ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : name,
                anno, annoProperties);
        properties.put(property.getName(), property);
        ProxyEvent event = property.getEvent();
        if (event != null)
            events.put(event.getName(), event);
    }

    // Classes need to have all inherited properties added
    if (!clazz.isInterface()) {
        for (ProxyType ifc : interfaces)
            addProperties((ProxyTypeImpl) ifc, properties);
    }

    // Remove property accessors
    for (ProxyProperty prop : properties.values())
        methodsCompiler.removePropertyAccessors((ProxyPropertyImpl) prop);

    // Load events
    if (clazz.isAnnotationPresent(Events.class)) {
        Events annoEvents = (Events) clazz.getAnnotation(Events.class);
        for (Event annoEvent : annoEvents.value()) {
            if (!events.containsKey(annoEvent.value()))
                events.put(annoEvent.value(), new ProxyEvent(annoEvent));
        }
    }

    // Classes need to have all inherited events added
    if (!clazz.isInterface()) {
        for (ProxyType type : interfaces)
            addEvents((ProxyTypeImpl) type, events);
    }

    // Save
    this.properties = properties.isEmpty() ? null : properties;
    this.events = events.isEmpty() ? null : events;
    this.methods = methodsCompiler.toArray();
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

private void orderReloadableBeans(Set<Class<? extends ReloadableBean>> beansLeftToInit,
        Class<? extends ReloadableBean> beanClass) {
    if (!beansLeftToInit.contains(beanClass)) {
        // Already done
        return;//from  www  .ja  v a  2  s.  co m
    }
    ReloadableBean initializingBean = beanForType(beanClass);
    Class<?> targetClass = AopUtils.getTargetClass(initializingBean);
    Reloadable annotation;
    if (targetClass.isAnnotationPresent(Reloadable.class)) {
        annotation = targetClass.getAnnotation(Reloadable.class);
    } else {
        throw new IllegalStateException(
                "Bean " + targetClass.getName() + " requires the @Reloadable annotation to be present.");
    }
    Class<? extends ReloadableBean>[] dependsUpon = annotation.initAfter();
    for (Class<? extends ReloadableBean> doBefore : dependsUpon) {
        //Sanity check that prerequisite bean was registered
        if (!toInitialize.contains(doBefore)) {
            throw new IllegalStateException("Bean '" + beanClass.getName() + "' requires bean '"
                    + doBefore.getName() + "' to be initialized, but no such bean is registered for init.");
        }
        if (!doBefore.isInterface()) {
            throw new IllegalStateException("Cannot order bean with implementation class.\n"
                    + " Please provide an interface extending " + ReloadableBean.class.getName());
        }
        orderReloadableBeans(beansLeftToInit, doBefore);
    }
    // Avoid double init
    if (beansLeftToInit.remove(beanClass)) {
        reloadableBeans.add(initializingBean);
    }
}

From source file:com.opensymphony.xwork2.util.LocalizedTextUtil.java

/**
 * Traverse up class hierarchy looking for message.  Looks at class, then implemented interface,
 * before going up hierarchy./*from www.j a  v  a  2 s . c  o  m*/
 */
private static String findMessage(Class clazz, String key, String indexedKey, Locale locale, Object[] args,
        Set<String> checked, ValueStack valueStack) {
    if (checked == null) {
        checked = new TreeSet<String>();
    } else if (checked.contains(clazz.getName())) {
        return null;
    }

    // look in properties of this class
    String msg = getMessage(clazz.getName(), locale, key, valueStack, args);

    if (msg != null) {
        return msg;
    }

    if (indexedKey != null) {
        msg = getMessage(clazz.getName(), locale, indexedKey, valueStack, args);

        if (msg != null) {
            return msg;
        }
    }

    // look in properties of implemented interfaces
    Class[] interfaces = clazz.getInterfaces();

    for (Class anInterface : interfaces) {
        msg = getMessage(anInterface.getName(), locale, key, valueStack, args);

        if (msg != null) {
            return msg;
        }

        if (indexedKey != null) {
            msg = getMessage(anInterface.getName(), locale, indexedKey, valueStack, args);

            if (msg != null) {
                return msg;
            }
        }
    }

    // traverse up hierarchy
    if (clazz.isInterface()) {
        interfaces = clazz.getInterfaces();

        for (Class anInterface : interfaces) {
            msg = findMessage(anInterface, key, indexedKey, locale, args, checked, valueStack);

            if (msg != null) {
                return msg;
            }
        }
    } else {
        if (!clazz.equals(Object.class) && !clazz.isPrimitive()) {
            return findMessage(clazz.getSuperclass(), key, indexedKey, locale, args, checked, valueStack);
        }
    }

    return null;
}

From source file:org.jadira.scanner.classpath.types.JParameter.java

@Override
public JType getType() throws ClasspathAccessException {

    Class<?> clazz;
    if (enclosingOperation instanceof JConstructor || enclosingOperation instanceof JMethod) {
        MethodInfo methodInfo = ((JOperation) enclosingOperation).getMethodInfo();
        String[] paramTypeNames = JavassistMethodInfoHelper.getMethodParamTypeNames(methodInfo);
        clazz = decodeFieldType(paramTypeNames[getIndex()]);

    } else {// www . j  ava  2 s. c  om
        throw new ClasspathAccessException("Invalid parameter index: " + index);
    }

    if (clazz.isAnnotation()) {
        try {
            return new JAnnotation<java.lang.annotation.Annotation>(
                    (java.lang.annotation.Annotation) clazz.newInstance(), this, getResolver());
        } catch (InstantiationException e) {
            throw new ClasspathAccessException("Problem instantiating annotation: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new ClasspathAccessException("Problem accessing annotation: " + e.getMessage(), e);
        }
    } else if (clazz.isInterface()) {
        return new JInterface(clazz.getName(), getResolver());
    } else {
        JClass jClass = new JClass(clazz.getName(), getResolver());
        return jClass;
    }
}