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:edu.cornell.mannlib.vedit.util.FormUtils.java

/**
 * Populates form objects with bean values
 *//*from w  w w .j  a  va  2  s.  co  m*/
public static void populateFormFromBean(Object bean, String action, EditProcessObject epo, FormObject foo,
        Map<String, String> BadValuesHash) {
    Class beanClass = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : bean.getClass();

    Method[] meths = beanClass.getMethods();

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

        if (meths[i].getName().indexOf("set") == 0) {

            // we have a setter method
            Method currMeth = meths[i];
            Class[] currMethParamTypes = currMeth.getParameterTypes();
            Class currMethType = currMethParamTypes[0];

            if (SUPPORTED_TYPE_LIST.contains(currMethType)) {
                //we only want people directly to type in ints, strings, and dates
                //of course, most of the ints are probably foreign keys anyway...

                String elementName = currMeth.getName().substring(3, currMeth.getName().length());

                //see if there's something in the bean using
                //the related getter method

                Class[] paramClass = new Class[1];
                paramClass[0] = currMethType;
                try {
                    Method getter = beanClass.getMethod("get" + elementName, (Class[]) null);
                    Object existingData = null;
                    try {
                        existingData = getter.invoke(bean, (Object[]) null);
                    } catch (Exception e) {
                        log.error("Exception invoking getter method");
                    }
                    String value = "";
                    if (existingData != null) {
                        if (existingData instanceof String) {
                            value += existingData;
                        } else if (!(existingData instanceof Integer && (Integer) existingData < 0)) {
                            value += existingData.toString();
                        }
                    }
                    String badValue = (String) BadValuesHash.get(elementName);
                    if (badValue != null) {
                        value = badValue;
                    }
                    foo.getValues().put(elementName, value);
                } catch (NoSuchMethodException e) {
                    //ignore it
                }
            }
        }
    }
}

From source file:com.swingtech.commons.testing.JavaBeanTester.java

/**
 * Tests the get/set methods of the specified class.
 * /*w  ww  .j av  a  2  s  . c  om*/
 * @param <T> the type parameter associated with the class under test
 * @param clazz the Class under test
 * @param skipThese the names of any properties that should not be tested
 * @throws IntrospectionException thrown if the Introspector.getBeanInfo() method throws this exception 
 * for the class under test
 */
public static <T> void test(final Class<T> clazz, final String... skipThese) throws IntrospectionException {
    final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    nextProp: for (PropertyDescriptor prop : props) {
        // Check the list of properties that we don't want to test
        for (String skipThis : skipThese) {
            if (skipThis.equals(prop.getName())) {
                continue nextProp;
            }
        }
        final Method getter = prop.getReadMethod();
        final Method setter = prop.getWriteMethod();

        if (getter != null && setter != null) {
            // We have both a get and set method for this property
            final Class<?> returnType = getter.getReturnType();
            final Class<?>[] params = setter.getParameterTypes();

            if (params.length == 1 && params[0] == returnType) {
                // The set method has 1 argument, which is of the same type as the return type of the get method, so we can test this property
                try {
                    // Build a value of the correct type to be passed to the set method
                    Object value = buildValue(returnType);

                    // Build an instance of the bean that we are testing (each property test gets a new instance)
                    T bean = clazz.newInstance();

                    // Call the set method, then check the same value comes back out of the get method
                    setter.invoke(bean, value);

                    final Object expectedValue = value;
                    final Object actualValue = getter.invoke(bean);

                    assertEquals(String.format("Failed while testing property %s", prop.getName()),
                            expectedValue, actualValue);

                } catch (Exception ex) {
                    fail(String.format("An exception was thrown while testing the property %s: %s",
                            prop.getName(), ex.toString()));
                }
            }
        }
    }
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return signature for given {@link Method}. This signature is not same signature as in JVM or JDT, just
 *         some string that unique identifies method in its {@link Class}.
 *///from www  . j av  a  2  s .  com
public static String getMethodSignature(Method method) {
    Assert.isNotNull(method);
    return getMethodSignature(method.getName(), method.getParameterTypes());
}

From source file:com.wavemaker.runtime.server.ServerUtils.java

/**
 * Try to determine parameter names for a given method. This will check {@link ParamName} attributes and debugging
 * symbols; if no name can be found, a default "arg-&lt;position>" name will be used.
 * /*from   w w  w .  j a  v a  2 s  . c o  m*/
 * This will also continue working of method has been loaded by a non-default classloader.
 * 
 * @param method The method to introspect.
 * @return The names of the parameters in an ordered list.
 */
public static List<String> getParameterNames(Method method) {

    int numParams = method.getParameterTypes().length;
    List<String> ret = new ArrayList<String>(numParams);
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    Class<?> paramNameClass = ClassLoaderUtils.loadClass(ParamName.class.getName(),
            method.getDeclaringClass().getClassLoader());

    String[] methodParameterNames;

    try {
        AdaptiveParanamer ap = new AdaptiveParanamer();
        methodParameterNames = ap.lookupParameterNames(method);
        ap = null;
    } catch (ParameterNamesNotFoundException e) {
        logger.info("No parameter names found for method " + method.getName());
        methodParameterNames = new String[numParams];
    }

    for (int i = 0; i < numParams; i++) {
        String paramName = null;

        if (paramName == null) {
            for (Annotation ann : paramAnnotations[i]) {
                if (paramNameClass.isAssignableFrom(ann.annotationType())) {
                    try {
                        Method nameMethod = paramNameClass.getMethod("name");
                        paramName = (String) nameMethod.invoke(ann);
                    } catch (SecurityException e) {
                        throw new WMRuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new WMRuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new WMRuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new WMRuntimeException(e);
                    }

                    break;
                }
            }
        }

        if (paramName == null && methodParameterNames != null) {
            paramName = methodParameterNames[i];
        }

        if (paramName == null) {
            logger.warn("no parameter name information for parameter " + i + ", method: " + method.getName());
            paramName = "arg-" + (i + 1);
        }

        ret.add(paramName);
    }

    return ret;
}

From source file:springfox.documentation.spring.web.readers.operation.HandlerMethodResolver.java

private static Iterable<ResolvedMethod> methodsWithSameNumberOfParams(Iterable<ResolvedMethod> filtered,
        final Method methodToResolve) {

    return filter(filtered, new Predicate<ResolvedMethod>() {
        @Override//  ww  w. java  2  s . com
        public boolean apply(ResolvedMethod input) {
            return input.getArgumentCount() == methodToResolve.getParameterTypes().length;
        }
    });
}

From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java

/**
 * ?//from  w  w  w  .j  av  a 2 s.  c  o m
 * 
 * @param method
 * @param model
 * @param request
 * @param response
 * @param c
 * @return
 */
@SuppressWarnings("unchecked")
public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response, Class<?> c) {
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    Map<String, String> pathValues = null;
    PathPattern pathPattern = method.getAnnotation(PathPattern.class);
    if (pathPattern != null) {
        String path = request.getRequestURI();
        int index = path.lastIndexOf('.');
        if (index != -1) {
            path = path.substring(0, index);
            String[] patterns = pathPattern.patterns();
            pathValues = getPathValues(patterns, path);
        }
    }
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        MethodParameter methodParam = new MethodParameter(method, i);
        methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, c.getClass());

        String paramName = methodParam.getParameterName();
        // map
        if (Map.class.isAssignableFrom(paramType)) {
            args[i] = model;
        }
        // HttpServletRequest
        else if (HttpServletRequest.class.isAssignableFrom(paramType)) {
            args[i] = request;
        }
        // HttpServletResponse
        else if (HttpServletResponse.class.isAssignableFrom(paramType)) {
            args[i] = response;
        }
        // HttpSession
        else if (HttpSession.class.isAssignableFrom(paramType)) {
            args[i] = request.getSession();
        }
        // Errors
        else if (Errors.class.isAssignableFrom(paramType)) {
            args[i] = errors;
        }
        // MultipartFile
        else if (MultipartFile.class.isAssignableFrom(paramType)) {
            MultipartFile[] files = resolveMultipartFiles(request, errors, paramName);
            if (files != null && files.length > 0) {
                args[i] = files[0];
            }
        }
        // MultipartFile[]
        else if (MultipartFile[].class.isAssignableFrom(paramType)) {
            args[i] = resolveMultipartFiles(request, errors, paramName);
        } else {
            // ??
            if (BeanUtils.isSimpleProperty(paramType)) {
                SimpleTypeConverter converter = new SimpleTypeConverter();
                Object value;
                // ?
                if (paramType.isArray()) {
                    value = request.getParameterValues(paramName);
                } else {
                    Object[] parameterAnnotations = methodParam.getParameterAnnotations();
                    value = null;
                    if (parameterAnnotations != null && parameterAnnotations.length > 0) {
                        if (pathValues != null && pathValues.size() > 0) {
                            for (Object object : parameterAnnotations) {
                                if (PathVariable.class.isInstance(object)) {
                                    PathVariable pv = (PathVariable) object;
                                    if (StringUtils.isEmpty(pv.value())) {
                                        value = pathValues.get(paramName);
                                    } else {
                                        value = pathValues.get(pv.value());
                                    }
                                    break;
                                }
                            }
                        }
                    } else {
                        value = request.getParameter(paramName);
                    }
                }
                try {
                    args[i] = converter.convertIfNecessary(value, paramType, methodParam);
                    model.put(paramName, args[i]);
                } catch (TypeMismatchException e) {
                    errors.addError(new FieldError(paramName, paramName, e.getMessage()));
                }
            } else {
                // ???POJO
                if (paramType.isArray()) {
                    ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(),
                            paramName);
                    args[i] = binder.bind(request);
                    model.put(paramName, args[i]);
                } else {
                    Object bindObject = BeanUtils.instantiateClass(paramType);
                    SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject,
                            paramName);
                    binder.bind(request);
                    BindException be = new BindException(binder.getBindingResult());
                    List<FieldError> fieldErrors = be.getFieldErrors();
                    for (FieldError fieldError : fieldErrors) {
                        errors.addError(fieldError);
                    }
                    args[i] = binder.getTarget();
                    model.put(paramName, args[i]);
                }
            }
        }
    }
    return args;
}

From source file:ch.ralscha.extdirectspring.util.MethodInfo.java

private static List<ParameterInfo> buildParameterList(Class<?> clazz, Method method) {
    List<ParameterInfo> params = new ArrayList<ParameterInfo>();

    Class<?>[] parameterTypes = method.getParameterTypes();

    Method methodWithAnnotation = findMethodWithAnnotation(method, ExtDirectMethod.class);
    if (methodWithAnnotation == null) {
        methodWithAnnotation = method;/*from  ww  w. j a  v  a2  s  . c  o  m*/
    }

    for (int paramIndex = 0; paramIndex < parameterTypes.length; paramIndex++) {
        params.add(new ParameterInfo(clazz, methodWithAnnotation, paramIndex));
    }

    return params;
}

From source file:com.weibo.api.motan.protocol.yar.YarProtocolUtil.java

/**
 * add arguments/*from w  w  w  . j  av  a  2 s . c o  m*/
 * 
 * @param interfaceClass
 * @param methodName
 * @param arguments
 * @return
 */
private static void addArguments(DefaultRequest request, Class<?> interfaceClass, String methodName,
        Object[] arguments) {
    Method targetMethod = null;
    Method[] methods = interfaceClass.getDeclaredMethods();
    for (Method m : methods) {
        // FIXME parameters may be ambiguous in weak type language, temporarily by limiting the
        // size of parameters with same method name to avoid.
        if (m.getName().equalsIgnoreCase(methodName) && m.getParameterTypes().length == arguments.length) {
            targetMethod = m;
            break;
        }
    }
    if (targetMethod == null) {
        throw new MotanServiceException("cann't find request method. method name " + methodName);
    }

    request.setParamtersDesc(ReflectUtil.getMethodParamDesc(targetMethod));

    if (arguments != null && arguments.length > 0) {
        Class<?>[] argumentClazz = targetMethod.getParameterTypes();
        request.setArguments(adaptParams(targetMethod, arguments, argumentClazz));
    }

}

From source file:com.espertech.esper.util.MethodResolver.java

private static void logWarnBoxedToPrimitiveType(Class declaringClass, String methodName, Method bestMatch,
        Class[] paramTypes) {/*from  ww w.  ja v a  2  s .  c o m*/
    Class[] parametersMethod = bestMatch.getParameterTypes();
    for (int i = 0; i < parametersMethod.length; i++) {
        if (!parametersMethod[i].isPrimitive()) {
            continue;
        }
        // if null-type parameter, or non-JDK class and boxed type matches
        if (paramTypes[i] == null || (!declaringClass.getClass().getName().startsWith("java")
                && (JavaClassHelper.getBoxedType(parametersMethod[i])) == paramTypes[i])) {
            String paramTypeStr = paramTypes[i] == null ? "null" : paramTypes[i].getSimpleName();
            log.info("Method '" + methodName + "' in class '" + declaringClass.getName()
                    + "' expects primitive type '" + parametersMethod[i] + "' as parameter " + i
                    + ", but receives a nullable (boxed) type " + paramTypeStr
                    + ". This may cause null pointer exception at runtime if the actual value is null, please consider using boxed types for method parameters.");
            return;
        }
    }
}

From source file:io.fabric8.spring.boot.AbstractServiceRegistar.java

private static Class getSourceType(Method method) {
    Annotation[][] annotations = method.getParameterAnnotations();
    for (int i = 0; i < annotations.length; i++) {
        for (int j = 0; j < annotations[i].length; j++) {
            if (ServiceName.class.equals(annotations[i][j].annotationType())) {
                return method.getParameterTypes()[i];
            }/*from   w w w.  java  2 s  .c  o  m*/
        }
    }
    throw new IllegalStateException("No source type found for @Factory:" + method.getName());
}