Example usage for java.lang.reflect Method getParameterTypes

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

Introduction

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

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:cn.aposoft.util.spring.ReflectionUtils.java

/**
 * Get the unique set of declared methods on the leaf class and all
 * superclasses. Leaf class methods are included first and while traversing
 * the superclass hierarchy any methods found with signatures matching a
 * method already included are filtered out.
 * /*from   w w  w .jav  a 2 s  . c o m*/
 * @param leafClass
 *            the class to introspect
 */
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
    final List<Method> methods = new ArrayList<Method>(32);
    doWithMethods(leafClass, new MethodCallback() {
        @Override
        public void doWith(Method method) {
            boolean knownSignature = false;
            Method methodBeingOverriddenWithCovariantReturnType = null;
            for (Method existingMethod : methods) {
                if (method.getName().equals(existingMethod.getName())
                        && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
                    // Is this a covariant return type situation?
                    if (existingMethod.getReturnType() != method.getReturnType()
                            && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
                        methodBeingOverriddenWithCovariantReturnType = existingMethod;
                    } else {
                        knownSignature = true;
                    }
                    break;
                }
            }
            if (methodBeingOverriddenWithCovariantReturnType != null) {
                methods.remove(methodBeingOverriddenWithCovariantReturnType);
            }
            if (!knownSignature && !isCglibRenamedMethod(method)) {
                methods.add(method);
            }
        }
    });
    return methods.toArray(new Method[methods.size()]);
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

public static Method findMethod(Class start, String methodName, int argCount) {
    // For overridden methods we need to find the most derived version.
    // So we start with the given class and walk up the superclass chain.
    for (Class cl = start; cl != null; cl = cl.getSuperclass()) {
        Method methods[] = getPublicDeclaredMethods(cl);
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method == null) {
                continue;
            }//from   ww  w  .  j av a  2s .c  o m
            // skip static methods.
            int mods = method.getModifiers();
            if (Modifier.isStatic(mods)) {
                continue;
            }
            if (method.getName().equals(methodName) && method.getParameterTypes().length == argCount) {
                return method;
            }
        }
    }

    // Now check any inherited interfaces.  This is necessary both when
    // the argument class is itself an interface, and when the argument
    // class is an abstract class.
    Class ifcs[] = start.getInterfaces();
    for (int i = 0; i < ifcs.length; i++) {
        Method m = findMethod(ifcs[i], methodName, argCount);
        if (m != null) {
            return m;
        }
    }

    return null;
}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

@SuppressWarnings("unchecked")
public static List<IParameter> getResourceParameters(final FhirContext theContext, Method theMethod,
        Object theProvider, RestOperationTypeEnum theRestfulOperationTypeEnum) {
    List<IParameter> parameters = new ArrayList<IParameter>();

    Class<?>[] parameterTypes = theMethod.getParameterTypes();
    int paramIndex = 0;
    for (Annotation[] annotations : theMethod.getParameterAnnotations()) {

        IParameter param = null;/*w  w w.j  a  va2s  . c o m*/
        Class<?> parameterType = parameterTypes[paramIndex];
        Class<? extends java.util.Collection<?>> outerCollectionType = null;
        Class<? extends java.util.Collection<?>> innerCollectionType = null;
        if (SearchParameterMap.class.equals(parameterType)) {
            if (theProvider instanceof IDynamicSearchResourceProvider) {
                Search searchAnnotation = theMethod.getAnnotation(Search.class);
                if (searchAnnotation != null && searchAnnotation.dynamic()) {
                    param = new DynamicSearchParameter((IDynamicSearchResourceProvider) theProvider);
                }
            }
        } else if (TagList.class.isAssignableFrom(parameterType)) {
            // TagList is handled directly within the method bindings
            param = new NullParameter();
        } else {
            if (Collection.class.isAssignableFrom(parameterType)) {
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                outerCollectionType = innerCollectionType;
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                throw new ConfigurationException("Argument #" + paramIndex + " of Method '"
                        + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName()
                        + "' is of an invalid generic type (can not be a collection of a collection of a collection)");
            }
        }

        /* 
         * Note: for the frst two here, we're using strings instead of static binding
         * so that we don't need the java.servlet JAR on the classpath in order to use
         * this class 
         */
        if (ourServletRequestTypes.contains(parameterType.getName())) {
            param = new ServletRequestParameter();
        } else if (ourServletResponseTypes.contains(parameterType.getName())) {
            param = new ServletResponseParameter();
        } else if (parameterType.equals(RequestDetails.class)) {
            param = new RequestDetailsParameter();
        } else if (parameterType.equals(IRequestOperationCallback.class)) {
            param = new RequestOperationCallbackParameter();
        } else if (parameterType.equals(SummaryEnum.class)) {
            param = new SummaryEnumParameter();
        } else if (parameterType.equals(PatchTypeEnum.class)) {
            param = new PatchTypeParameter();
        } else {
            for (int i = 0; i < annotations.length && param == null; i++) {
                Annotation nextAnnotation = annotations[i];

                if (nextAnnotation instanceof RequiredParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((RequiredParam) nextAnnotation).name());
                    parameter.setRequired(true);
                    parameter.setDeclaredTypes(((RequiredParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((RequiredParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((RequiredParam) nextAnnotation).chainWhitelist(),
                            ((RequiredParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof OptionalParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((OptionalParam) nextAnnotation).name());
                    parameter.setRequired(false);
                    parameter.setDeclaredTypes(((OptionalParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((OptionalParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((OptionalParam) nextAnnotation).chainWhitelist(),
                            ((OptionalParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof IncludeParam) {
                    Class<? extends Collection<Include>> instantiableCollectionType;
                    Class<?> specType;

                    if (parameterType == String.class) {
                        instantiableCollectionType = null;
                        specType = String.class;
                    } else if ((parameterType != Include.class) || innerCollectionType == null
                            || outerCollectionType != null) {
                        throw new ConfigurationException("Method '" + theMethod.getName()
                                + "' is annotated with @" + IncludeParam.class.getSimpleName()
                                + " but has a type other than Collection<" + Include.class.getSimpleName()
                                + ">");
                    } else {
                        instantiableCollectionType = (Class<? extends Collection<Include>>) CollectionBinder
                                .getInstantiableCollectionType(innerCollectionType,
                                        "Method '" + theMethod.getName() + "'");
                        specType = parameterType;
                    }

                    param = new IncludeParameter((IncludeParam) nextAnnotation, instantiableCollectionType,
                            specType);
                } else if (nextAnnotation instanceof ResourceParam) {
                    Mode mode;
                    if (IBaseResource.class.isAssignableFrom(parameterType)) {
                        mode = Mode.RESOURCE;
                    } else if (String.class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY;
                    } else if (byte[].class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY_BYTE_ARRAY;
                    } else if (EncodingEnum.class.equals(parameterType)) {
                        mode = Mode.ENCODING;
                    } else {
                        StringBuilder b = new StringBuilder();
                        b.append("Method '");
                        b.append(theMethod.getName());
                        b.append("' is annotated with @");
                        b.append(ResourceParam.class.getSimpleName());
                        b.append(" but has a type that is not an implemtation of ");
                        b.append(IBaseResource.class.getCanonicalName());
                        b.append(" or String or byte[]");
                        throw new ConfigurationException(b.toString());
                    }
                    param = new ResourceParameter((Class<? extends IResource>) parameterType, theProvider,
                            mode);
                } else if (nextAnnotation instanceof IdParam || nextAnnotation instanceof VersionIdParam) {
                    param = new NullParameter();
                } else if (nextAnnotation instanceof ServerBase) {
                    param = new ServerBaseParamBinder();
                } else if (nextAnnotation instanceof Elements) {
                    param = new ElementsParameter();
                } else if (nextAnnotation instanceof Since) {
                    param = new SinceParameter();
                    ((SinceParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof At) {
                    param = new AtParameter();
                    ((AtParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof Count) {
                    param = new CountParameter();
                } else if (nextAnnotation instanceof Sort) {
                    param = new SortParameter(theContext);
                } else if (nextAnnotation instanceof TransactionParam) {
                    param = new TransactionParameter(theContext);
                } else if (nextAnnotation instanceof ConditionalUrlParam) {
                    param = new ConditionalParamBinder(theRestfulOperationTypeEnum,
                            ((ConditionalUrlParam) nextAnnotation).supportsMultiple());
                } else if (nextAnnotation instanceof OperationParam) {
                    Operation op = theMethod.getAnnotation(Operation.class);
                    param = new OperationParameter(theContext, op.name(), ((OperationParam) nextAnnotation));
                } else if (nextAnnotation instanceof Validate.Mode) {
                    if (parameterType.equals(ValidationModeEnum.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Mode.class.getSimpleName()
                                + " must be of type " + ValidationModeEnum.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_MODE, 0, 1).setConverter(new IOperationParamConverter() {
                                @Override
                                public Object incomingServer(Object theObject) {
                                    if (isNotBlank(theObject.toString())) {
                                        ValidationModeEnum retVal = ValidationModeEnum
                                                .forCode(theObject.toString());
                                        if (retVal == null) {
                                            OperationParameter.throwInvalidMode(theObject.toString());
                                        }
                                        return retVal;
                                    } else {
                                        return null;
                                    }
                                }

                                @Override
                                public Object outgoingClient(Object theObject) {
                                    return ParametersUtil.createString(theContext,
                                            ((ValidationModeEnum) theObject).getCode());
                                }
                            });
                } else if (nextAnnotation instanceof Validate.Profile) {
                    if (parameterType.equals(String.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Profile.class.getSimpleName()
                                + " must be of type " + String.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_PROFILE, 0, 1)
                                    .setConverter(new IOperationParamConverter() {
                                        @Override
                                        public Object incomingServer(Object theObject) {
                                            return theObject.toString();
                                        }

                                        @Override
                                        public Object outgoingClient(Object theObject) {
                                            return ParametersUtil.createString(theContext,
                                                    theObject.toString());
                                        }
                                    });
                } else {
                    continue;
                }

            }

        }

        if (param == null) {
            throw new ConfigurationException("Parameter #" + ((paramIndex + 1)) + "/" + (parameterTypes.length)
                    + " of method '" + theMethod.getName() + "' on type '"
                    + theMethod.getDeclaringClass().getCanonicalName()
                    + "' has no recognized FHIR interface parameter annotations. Don't know how to handle this parameter");
        }

        param.initializeTypes(theMethod, outerCollectionType, innerCollectionType, parameterType);
        parameters.add(param);

        paramIndex++;
    }
    return parameters;
}

From source file:com.cuubez.visualizer.processor.ResourceVariableProcessor.java

public void process() {

    List<RootResource> rootResourceList = InformationRepository.getInstance().getRootResources();

    for (RootResource rootResource : rootResourceList) {

        for (SubResource subResource : rootResource.getSubResources()) {

            Method selectedMethod = subResource.getReflectionMethod();
            final Class[] paramTypes = selectedMethod.getParameterTypes();

            final Annotation[][] paramAnnotations = selectedMethod.getParameterAnnotations();

            for (int i = 0; i < paramAnnotations.length; i++) {

                boolean pathParam = false;
                boolean queryParam = false;
                boolean headerParam = false;
                boolean mandatory = false;
                String name = null;
                String parameterDetail = null;

                for (Annotation annotation : paramAnnotations[i]) {

                    if (annotation instanceof PathParam) {
                        name = ((PathParam) annotation).value();
                        pathParam = true;

                    } else if (annotation instanceof QueryParam) {

                        name = ((QueryParam) annotation).value();
                        queryParam = true;

                    } else if (annotation instanceof HeaderParam) {

                        name = ((HeaderParam) annotation).value();
                        headerParam = true;

                    } else if (annotation instanceof M) {
                        mandatory = true;
                    } else if (annotation instanceof ParameterDetail) {
                        parameterDetail = ((ParameterDetail) annotation).value();
                    }//from w w  w  .  jav a2s.  co  m
                }

                if (!pathParam && !headerParam && !queryParam) {
                    subResource.setRequestBody(paramTypes[i]);
                }

                constructPathVariableContext(name, pathParam, parameterDetail, paramTypes[i], subResource);
                constructQueryVariableContext(name, queryParam, parameterDetail, mandatory, paramTypes[i],
                        subResource);
                constructHeaderVariableContext(name, headerParam, parameterDetail, mandatory, paramTypes[i],
                        subResource);

            }

        }
    }

}

From source file:com.glaf.core.util.ReflectUtils.java

/**
 * Returns the setter-method for the given field name or null if no setter
 * exists./*from   w  w  w. j a  v  a2s .c  o m*/
 */
public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) {
    String setterName = "set" + Character.toTitleCase(fieldName.charAt(0))
            + fieldName.substring(1, fieldName.length());
    try {
        // Using getMathods(), getMathod(...) expects exact parameter type
        // matching and ignores inheritance-tree.
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(setterName)) {
                Class<?>[] paramTypes = method.getParameterTypes();
                if (paramTypes != null && paramTypes.length == 1 && paramTypes[0].isAssignableFrom(fieldType)) {
                    return method;
                }
            }
        }
        return null;
    } catch (SecurityException e) {
        throw new RuntimeException(
                "Not allowed to access method " + setterName + " on class " + clazz.getCanonicalName());
    }
}

From source file:controllerTas.config.xml.TasControllerConfigXmlParser.java

private Class getClassMethodIfExists(Class c, String method) {
    Method[] declared = c.getDeclaredMethods();
    for (Method aDeclared : declared) {
        if (aDeclared.getName().equals(method)) {
            Class[] array = aDeclared.getParameterTypes();
            if (array.length > 1) {
                throw new RuntimeException(
                        "Ho trovato il metodo " + method + "ma non  un setter con un solo parametro!");
            } else
                return array[0];
        }// www  . j a  va  2 s  . c om
    }
    return null;
}

From source file:pl.com.bottega.ecommerce.system.saga.impl.SpringSagaRegistry.java

private void registerSagaLoader(Class<?> loaderClass, String beanName) {
    for (Method method : loaderClass.getMethods()) {
        if (method.getAnnotation(SagaAction.class) != null || method.getAnnotation(LoadSaga.class) != null) {
            Class<?>[] params = method.getParameterTypes();
            if (params.length == 1) {
                loadersInterestedIn.put(params[0], beanName);
            } else {
                throw new RuntimeException("incorred event hadndler: " + method);
            }//from   ww w .j ava  2s  .  co  m
        }
    }
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.EnableScanAnnotationPermissions.java

public EnableScanAnnotationPermissions(Class<?> repositoryInterface) {
    // Check to see if global EnableScan is declared at interface level
    if (repositoryInterface.isAnnotationPresent(EnableScan.class)) {
        this.findAllUnpaginatedScanEnabled = true;
        this.countUnpaginatedScanEnabled = true;
        this.deleteAllUnpaginatedScanEnabled = true;
        this.findAllPaginatedScanEnabled = true;
    } else {/* w  w w. j  ava  2 s  .  c  o m*/
        // Check declared methods for EnableScan annotation
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(repositoryInterface);
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScan.class) || method.getParameterTypes().length > 0) {
                // Only consider methods which have the EnableScan
                // annotation and which accept no parameters
                continue;
            }

            if (method.getName().equals("findAll")) {
                findAllUnpaginatedScanEnabled = true;
                continue;
            }

            if (method.getName().equals("deleteAll")) {
                deleteAllUnpaginatedScanEnabled = true;
                continue;
            }

            if (method.getName().equals("count")) {
                countUnpaginatedScanEnabled = true;
                continue;
            }

        }
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScanCount.class) || method.getParameterTypes().length != 1) {
                // Only consider methods which have the EnableScanCount
                // annotation and which have a single pageable parameter
                continue;
            }

            if (method.getName().equals("findAll")
                    && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) {
                findAllUnpaginatedScanCountEnabled = true;
                continue;
            }

        }
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScan.class) || method.getParameterTypes().length != 1) {
                // Only consider methods which have the EnableScan
                // annotation and which have a single pageable parameter
                continue;
            }

            if (method.getName().equals("findAll")
                    && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) {
                findAllPaginatedScanEnabled = true;
                continue;
            }

        }
    }
    if (!findAllUnpaginatedScanCountEnabled && repositoryInterface.isAnnotationPresent(EnableScanCount.class)) {
        findAllUnpaginatedScanCountEnabled = true;
    }

}

From source file:org.springmodules.validation.bean.conf.loader.annotation.handler.ValidationMethodAnnotationHandler.java

public boolean supports(Annotation annotation, Class clazz, Method method) {
    if (!super.supports(annotation, clazz, method)) {
        return false;
    }// www .  j  a v a2  s  . co  m
    return (method.getReturnType().equals(Boolean.class) || method.getReturnType().equals(boolean.class))
            && method.getParameterTypes().length == 0;
}

From source file:com.fortuityframework.spring.broker.SpringEventListenerLocator.java

private void registerMethodAsListener(ApplicationContext context, String beanDefinitionName, Method m) {
    OnFortuityEvent eventRef = m.getAnnotation(OnFortuityEvent.class);
    if (eventRef != null) {
        Class<?>[] paramTypes = m.getParameterTypes();
        if (paramTypes.length == 1 && EventContext.class.isAssignableFrom(paramTypes[0])) {
            Class<? extends Event<?>>[] events = getEvents(eventRef);

            for (Class<? extends Event<?>> eventClass : events) {
                registerListener(eventClass, beanDefinitionName, m, context);
            }//from  www.j  ava2 s .co m
        }
    }
}