Example usage for java.lang.reflect Method getParameterCount

List of usage examples for java.lang.reflect Method getParameterCount

Introduction

In this page you can find the example usage for java.lang.reflect Method getParameterCount.

Prototype

public int getParameterCount() 

Source Link

Usage

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

public List<String> extractOperationMethods(ApiOperation apiOperation, Method method,
        Iterator<SwaggerExtension> chain) {
    ArrayList<String> a = new ArrayList<>();
    if (apiOperation != null && apiOperation.httpMethod() != null && !"".equals(apiOperation.httpMethod())) {
        a.add(apiOperation.httpMethod().toLowerCase());
        return a;
    } else if (method.getAnnotation(RequestMapping.class) != null) {
        List<String> l = Arrays.asList(method.getAnnotation(RequestMapping.class).method()).stream()
                .map((org.thingsplode.synapse.core.RequestMethod rm) -> rm.toString().toLowerCase())
                .collect(Collectors.toList());
        if (l.isEmpty()) {
            if (method.getParameterCount() > 0 && (method.getAnnotations().length == 0
                    || method.getAnnotation(RequestBody.class) != null)) {
                //if there are parameters but not annotated at all or the RequestBody annotation is used
                l.add("put");
            } else if (method.getParameterCount() == 0 && !method.getReturnType().equals(Void.TYPE)) {
                //if there are no parameters but there's a return type
                l.add("get");
            } else {
                //if there are no parameters and no return type (void method)
                l.add("post");
            }/*from  w ww  .  j a v a 2 s .c  om*/
        }
        return l;
    } else if (SynapseEndpointServiceMarker.class.isAssignableFrom(method.getDeclaringClass())
            || method.getDeclaringClass().getAnnotation(Service.class) != null) {
        if (method.getParameterCount() > 0) {
            a.add("post");
        } else {
            a.add("get");
        }
        //todo: enable this when the service registry will support this differentiation
        //if (method.getReturnType().equals(Void.TYPE)) {
        //    a.add("post");
        //} else {
        //    a.add("get");
        //}
        return a;
    } else if ((ReflectionUtils.getOverriddenMethod(method)) != null) {
        return extractOperationMethods(apiOperation, ReflectionUtils.getOverriddenMethod(method), chain);
    } else if (chain != null && chain.hasNext()) {
        a.add(chain.next().extractOperationMethod(apiOperation, method, chain));
        return a;
    } else {
        return a;
    }
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private boolean isEntityWithLists(Method method, StoredProcedureInfo procedureInfo) {
    // method parameter 0: entity
    // method parameters [1..N]: lists
    boolean ok = procedureInfo.getArgumentsCounts() >= method.getParameterTypes().length - 1
            && method.getParameterTypes().length > 1
            && !BlockFactoryUtils.isSimpleType(method.getParameterTypes()[0])
            && !BlockFactoryUtils.isCollectionAssignableFrom(method.getParameterTypes()[0]);
    for (int i = 1; i < method.getParameterCount(); i++) {
        ok &= BlockFactoryUtils.isCollectionAssignableFrom(method.getParameterTypes()[i]);
    }/*  w  w  w. j a v  a  2 s . c  o  m*/
    return ok;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private boolean isEntityWithListsAndMetaLogin(Method method, StoredProcedureInfo procedureInfo) {
    // method parameter 0: entity
    // method parameters [1..N]: lists
    boolean ok = procedureInfo.getArgumentsCounts() - 2 >= method.getParameterTypes().length - 1
            && method.getParameterTypes().length > 1
            && !BlockFactoryUtils.isSimpleType(method.getParameterTypes()[0])
            && !BlockFactoryUtils.isCollectionAssignableFrom(method.getParameterTypes()[0]);
    for (int i = 1; i < method.getParameterCount(); i++) {
        ok &= BlockFactoryUtils.isCollectionAssignableFrom(method.getParameterTypes()[i]);
    }//from   www  .  j  a v a  2s.c  o  m
    return ok;
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

/**
 * Determine if the supplied {@code method} is an annotation attribute method.
 * @param method the method to check/*from  ww w. ja v  a2  s.  c om*/
 * @return {@code true} if the method is an attribute method
 * @since 4.2
 */
static boolean isAttributeMethod(@Nullable Method method) {
    return (method != null && method.getParameterCount() == 0 && method.getReturnType() != void.class);
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

/**
 * Determine if the supplied method is an "annotationType" method.
 * @return {@code true} if the method is an "annotationType" method
 * @see Annotation#annotationType()/*from  w w  w.ja v  a 2s . c om*/
 * @since 4.2
 */
static boolean isAnnotationTypeMethod(@Nullable Method method) {
    return (method != null && method.getName().equals("annotationType") && method.getParameterCount() == 0);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalFileTestExecutionListener.java

@Override
public void afterTestMethod(TestContext testContext) throws Exception {
    if (isTestClassAssignableFromOwncloudLocalFileTest(testContext)) {
        ApplicationContext applicationContext = testContext.getApplicationContext();

        Class<?> testClass = testContext.getTestClass();
        Method testMethod = testContext.getTestMethod();

        DisposableBean localDataService = applicationContext.getBean(OwncloudLocalUserDataServiceImpl.class);
        localDataService.destroy();// www. j  a va2 s. c  o  m

        ResourceLoader resourceLoader = applicationContext;
        OwncloudProperties properties = applicationContext.getBean(OwncloudProperties.class);
        Resource target = resourceLoader.getResource(properties.getLocation());

        boolean hasSpecificResourceTest = false;
        for (Method method : testContext.getTestClass().getMethods()) {
            // is this Method annotated by @CompareResourceAfter
            CompareResourceAfter compareResourceAfter = AnnotationUtils.findAnnotation(method,
                    CompareResourceAfter.class);
            if (compareResourceAfter == null
                    || !StringUtils.equals(compareResourceAfter.value(), testMethod.getName())) {
                continue;
            }

            // a Method annotated by @Test cannot also be annotated by
            // @CompareResourceAfter
            if (AnnotationUtils.findAnnotation(method, Test.class) != null) {
                log.warn("Method {} of Class {} cannot be annotated by {} and {}", method.getName(),
                        testClass.getName(), CompareResourceAfter.class, Test.class);
                continue;
            }

            // the @CompareResourceAfter annotated Method must have exactly 2
            // Parameters of Type org.springframework.core.io.Resource
            if (method.getParameterCount() != 1) {
                log.warn("Method {} of Class {} is annotated by {} but has {} Parameters instead of 1",
                        method.getName(), testClass.getName(), CompareResourceAfter.class.getName(),
                        method.getParameterCount());
                continue;
            }
            boolean correctParameterTypes = true;
            for (Class<?> parameterClass : method.getParameterTypes()) {
                correctParameterTypes = correctParameterTypes
                        && Resource.class.isAssignableFrom(parameterClass);
            }
            if (!correctParameterTypes) {
                log.warn("Method {} of Class {} (annotated by {}) must have 1 Parameter of Type {}",
                        method.getName(), testClass.getName(), CompareResourceAfter.class.getName(),
                        Resource.class.getName());
                continue;
            }

            log.debug("Call the Resource Comparsion Method {} on Class {}", method.getName(),
                    testClass.getName());
            hasSpecificResourceTest = true;
            try {
                method.invoke(testContext.getTestInstance(), target);
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof Exception) {
                    throw (Exception) e.getCause();
                }
                throw (Error) e.getCause();
            }
        }

        if (!hasSpecificResourceTest && ((OwncloudLocalFileTest) testContext.getTestInstance())
                .isCheckAllResourcesAgainstOriginal()) {
            compareResourcesWithOriginalSource(resourceLoader, target);
        }
    }
}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected void initProperties(Class<?> clazz, MetaClassImpl metaClass,
        Collection<MetadataObjectInitTask> tasks) {
    if (!metaClass.getOwnProperties().isEmpty())
        return;//from   ww  w  .  ja  v  a2 s .  c  om

    // load collection properties after non-collection in order to have all inverse properties loaded up
    ArrayList<Field> collectionProps = new ArrayList<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isSynthetic())
            continue;

        final String fieldName = field.getName();

        if (isMetaPropertyField(field)) {
            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(fieldName);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(field) || isMap(field)) {
                    collectionProps.add(field);
                } else {
                    info = loadProperty(metaClass, field);
                    tasks.addAll(info.getTasks());
                    MetaProperty metaProperty = info.getObject();
                    onPropertyLoaded(metaProperty, field);
                }
            } else {
                log.warn("Field " + clazz.getSimpleName() + "." + field.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }

    for (Field f : collectionProps) {
        MetadataObjectInfo<MetaProperty> info = loadCollectionProperty(metaClass, f);
        tasks.addAll(info.getTasks());
        MetaProperty metaProperty = info.getObject();
        onPropertyLoaded(metaProperty, f);
    }

    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isSynthetic())
            continue;

        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getReturnType() == void.class)
            continue;

        if (isMetaPropertyMethod(method)) {
            String name = StringUtils.uncapitalize(methodName.substring(3));

            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(name);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(method) || isMap(method)) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support collections and maps",
                                    clazz.getSimpleName(), method.getName()));
                } else if (method.getParameterCount() != 0) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support arguments",
                                    clazz.getSimpleName(), method.getName()));
                } else {
                    info = loadProperty(metaClass, method, name);
                    tasks.addAll(info.getTasks());
                }
                MetaProperty metaProperty = info.getObject();
                onPropertyLoaded(metaProperty, method);
            } else {
                log.warn("Method " + clazz.getSimpleName() + "." + method.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the setter method from the declaring class suitable to set a
 * value for the field.//ww  w. j  a  va2  s.  co m
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @return the setter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable setter
 */
private Method findSetterMethod(Class<?> declaringClass) {
    final String mname = "set" + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname, type);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        org.apache.commons.lang3.Validate.isTrue(m.getParameterCount() == 1,
                "expecting setter for field '%s' with one parameter", field);
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wptype = ClassUtils.primitiveToWrapper(DataTypeImpl.unwrapOptionalIfPresent(
                m.getParameterTypes()[0], m.getParameters()[0].getParameterizedType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wptype),
                "expecting setter for field '%s' with parameter type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected void initProperties(Class<?> clazz, MetaClassImpl metaClass, Collection<RangeInitTask> tasks) {
    if (!metaClass.getOwnProperties().isEmpty())
        return;/*from   w  w  w.j a  v  a 2s .co m*/

    // load collection properties after non-collection in order to have all inverse properties loaded up
    ArrayList<Field> collectionProps = new ArrayList<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isSynthetic())
            continue;

        final String fieldName = field.getName();

        if (isMetaPropertyField(field)) {
            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(fieldName);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(field) || isMap(field)) {
                    collectionProps.add(field);
                } else {
                    info = loadProperty(metaClass, field);
                    tasks.addAll(info.getTasks());
                    MetaProperty metaProperty = info.getObject();
                    onPropertyLoaded(metaProperty, field);
                }
            } else {
                log.warn("Field " + clazz.getSimpleName() + "." + field.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }

    for (Field f : collectionProps) {
        MetadataObjectInfo<MetaProperty> info = loadCollectionProperty(metaClass, f);
        tasks.addAll(info.getTasks());
        MetaProperty metaProperty = info.getObject();
        onPropertyLoaded(metaProperty, f);
    }

    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isSynthetic())
            continue;

        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getReturnType() == void.class)
            continue;

        if (isMetaPropertyMethod(method)) {
            String name = StringUtils.uncapitalize(methodName.substring(3));

            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(name);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(method) || isMap(method)) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support collections and maps",
                                    clazz.getSimpleName(), method.getName()));
                } else if (method.getParameterCount() != 0) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support arguments",
                                    clazz.getSimpleName(), method.getName()));
                } else {
                    info = loadProperty(metaClass, method, name);
                    tasks.addAll(info.getTasks());
                }
                MetaProperty metaProperty = info.getObject();
                onPropertyLoaded(metaProperty, method);
            } else {
                log.warn("Method " + clazz.getSimpleName() + "." + method.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Determine the target type for the given bean definition which is based on
 * a factory method. Only called if there is no singleton instance registered
 * for the target bean already.//from   w w w.  j a  va2 s . c om
 * <p>This implementation determines the type matching {@link #createBean}'s
 * different creation strategies. As far as possible, we'll perform static
 * type checking to avoid creation of the target bean.
 * @param beanName the name of the bean (for error handling purposes)
 * @param mbd the merged bean definition for the bean
 * @param typesToMatch the types to match in case of internal type matching purposes
 * (also signals that the returned {@code Class} will never be exposed to application code)
 * @return the type for the bean if determinable, or {@code null} otherwise
 * @see #createBean
 */
@Nullable
protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    ResolvableType cachedReturnType = mbd.factoryMethodReturnType;
    if (cachedReturnType != null) {
        return cachedReturnType.resolve();
    }

    Class<?> factoryClass;
    boolean isStatic = true;

    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "factory-bean reference points back to the same bean definition");
        }
        // Check declared factory method return type on factory class.
        factoryClass = getType(factoryBeanName);
        isStatic = false;
    } else {
        // Check declared factory method return type on bean class.
        factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
    }

    if (factoryClass == null) {
        return null;
    }
    factoryClass = ClassUtils.getUserClass(factoryClass);

    // If all factory methods have the same return type, return that type.
    // Can't clearly figure out exact method due to type converting / autowiring!
    Class<?> commonType = null;
    Method uniqueCandidate = null;
    int minNrOfArgs = (mbd.hasConstructorArgumentValues()
            ? mbd.getConstructorArgumentValues().getArgumentCount()
            : 0);
    Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(factoryClass,
            ReflectionUtils::getUniqueDeclaredMethods);

    for (Method candidate : candidates) {
        if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)
                && candidate.getParameterCount() >= minNrOfArgs) {
            // Declared type variables to inspect?
            if (candidate.getTypeParameters().length > 0) {
                try {
                    // Fully resolve parameter names and argument values.
                    Class<?>[] paramTypes = candidate.getParameterTypes();
                    String[] paramNames = null;
                    ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
                    if (pnd != null) {
                        paramNames = pnd.getParameterNames(candidate);
                    }
                    ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
                    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(
                            paramTypes.length);
                    Object[] args = new Object[paramTypes.length];
                    for (int i = 0; i < args.length; i++) {
                        ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(i,
                                paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
                        if (valueHolder == null) {
                            valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
                        }
                        if (valueHolder != null) {
                            args[i] = valueHolder.getValue();
                            usedValueHolders.add(valueHolder);
                        }
                    }
                    Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(candidate, args,
                            getBeanClassLoader());
                    uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ? candidate
                            : null);
                    commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
                    if (commonType == null) {
                        // Ambiguous return types found: return null to indicate "not determinable".
                        return null;
                    }
                } catch (Throwable ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed to resolve generic return type for factory method: " + ex);
                    }
                }
            } else {
                uniqueCandidate = (commonType == null ? candidate : null);
                commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType);
                if (commonType == null) {
                    // Ambiguous return types found: return null to indicate "not determinable".
                    return null;
                }
            }
        }
    }

    if (commonType == null) {
        return null;
    }
    // Common return type found: all factory methods return same type. For a non-parameterized
    // unique candidate, cache the full type declaration context of the target factory method.
    cachedReturnType = (uniqueCandidate != null ? ResolvableType.forMethodReturnType(uniqueCandidate)
            : ResolvableType.forClass(commonType));
    mbd.factoryMethodReturnType = cachedReturnType;
    return cachedReturnType.resolve();
}