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:com.edmunds.autotest.AutoTestGetterSetter.java

private Map<String, Method> mapPrefixedMethods(Collection<Method> methods, String[] prefixes, int paramCount) {
    Map<String, Method> result = new HashMap<String, Method>();

    for (Method method : methods) {
        if (method.getParameterTypes().length == paramCount && methodDeclaredUnderRootPackage(method)) {
            String baseName = getBaseName(method.getName().toLowerCase(), prefixes);

            if (baseName != null) {
                result.put(baseName, method);
            }//from w w  w .j av  a2s .  com
        }
    }
    return result;
}

From source file:com.github.dozermapper.core.converters.JAXBElementConverter.java

/**
 * Convert the specified input object into an output object of the
 * specified type./*ww  w .  j  a v a 2 s.  c o m*/
 *
 * @param type  Data type to which this value should be converted
 * @param value The input value to be converted
 * @return The converted value
 * @throws org.apache.commons.beanutils.ConversionException if conversion cannot be performed successfully
 */
@Override
public Object convert(Class type, Object value) {

    Object result;
    Object factory = objectFactory(destObjClass, beanContainer);
    Class<?> factoryClass = factory.getClass();
    Class<?> destClass = value.getClass();
    Class<?> valueClass = value.getClass();

    String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1)
            + StringUtils.capitalize(destFieldName);
    Method method = null;
    try {
        method = ReflectionUtils.findAMethod(factoryClass, methodName, beanContainer);
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (Class<?> parameterClass : parameterTypes) {
            if (!valueClass.equals(parameterClass)) {
                destClass = parameterClass;
                break;
            }
        }

        Class<?>[] paramTypes = { destClass };
        method = ReflectionUtils.getMethod(factoryClass, methodName, paramTypes);
    } catch (NoSuchMethodException e) {
        MappingUtils.throwMappingException(e);
    }

    Object param = value;
    Converter converter;
    if (java.util.Date.class.isAssignableFrom(valueClass) && !destClass.equals(XMLGregorianCalendar.class)) {
        converter = new DateConverter(dateFormat);
        param = converter.convert(destClass, param);
    } else if (java.util.Calendar.class.isAssignableFrom(valueClass)
            && !destClass.equals(XMLGregorianCalendar.class)) {
        converter = new CalendarConverter(dateFormat);
        param = converter.convert(destClass, param);
    } else if (XMLGregorianCalendar.class.isAssignableFrom(valueClass)
            || XMLGregorianCalendar.class.isAssignableFrom(destClass)) {
        converter = new XMLGregorianCalendarConverter(dateFormat);
        param = converter.convert(destClass, param);
    }

    Object[] paramValues = { param };
    result = ReflectionUtils.invoke(method, factory, paramValues);
    return result;
}

From source file:com.agileapes.couteau.context.spring.event.impl.GenericTranslationScheme.java

@Override
public void fillIn(Event originalEvent, ApplicationEvent translated) throws EventTranslationException {
    if (!(translated instanceof GenericApplicationEvent)) {
        return;/*  w w w.j  a v  a2 s.  com*/
    }
    GenericApplicationEvent applicationEvent = (GenericApplicationEvent) translated;
    final Enumeration<?> propertyNames = applicationEvent.getPropertyNames();
    while (propertyNames.hasMoreElements()) {
        final String property = (String) propertyNames.nextElement();
        final Object value = applicationEvent.getProperty(property);
        final Method method = ReflectionUtils.findMethod(originalEvent.getClass(),
                "set" + StringUtils.capitalize(property));
        if (method == null || !Modifier.isPublic(method.getModifiers())
                || method.getParameterTypes().length != 1 || !method.getReturnType().equals(void.class)
                || !method.getParameterTypes()[0].isInstance(value)) {
            continue;
        }
        try {
            method.invoke(originalEvent, value);
        } catch (Exception e) {
            throw new EventTranslationException("Failed to call setter on original event", e);
        }
    }
}

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

/**
 * get method name. "void do(int)", "void do()",
 * "int do(java.lang.String,boolean)"//from ww  w . jav a2  s. c  o  m
 * 
 * @param m
 *            method.
 * @return name.
 */
public static String getName(final Method m) {
    StringBuilder ret = new StringBuilder();
    ret.append(getName(m.getReturnType())).append(' ');
    ret.append(m.getName()).append('(');
    Class<?>[] parameterTypes = m.getParameterTypes();
    for (int i = 0; i < parameterTypes.length; i++) {
        if (i > 0)
            ret.append(',');
        ret.append(getName(parameterTypes[i]));
    }
    ret.append(')');
    return ret.toString();
}

From source file:org.kantega.dogmaticmvc.web.DefaultMethodParameterFactory.java

@Override
public Object[] getMethodParameters(Method method, HttpServletRequest req, HttpServletResponse resp,
        Map<String, Object> model) {
    Object[] params = new Object[method.getParameterTypes().length];

    try {/*from   ww w .ja v  a 2 s  .  c  o m*/
        for (int i = 0; i < method.getParameterTypes().length; i++) {
            Class parameterType = method.getParameterTypes()[i];
            RequestParam requestParam;
            SessionAttr sessionAttr;
            if (parameterType == ServletContext.class) {
                params[i] = servletContext;
            } else if (parameterType == HttpServletRequest.class) {
                params[i] = req;
            } else if (parameterType == HttpSession.class) {
                params[i] = req.getSession(true);
            } else if (parameterType == HttpServletResponse.class) {
                params[i] = resp;
            } else if (parameterType == OutputStream.class) {
                params[i] = resp.getOutputStream();
            } else if (parameterType == PrintWriter.class) {
                params[i] = resp.getWriter();
            } else if (parameterType == ServletOutputStream.class) {
                params[i] = resp.getOutputStream();
            } else if (parameterType == ApplicationContext.class && applicationContext != null) {
                params[i] = applicationContext;
            } else if (parameterType == Map.class) {
                params[i] = model;
            } else if ((requestParam = getParamAnnotation(method, i, RequestParam.class)) != null) {
                String name = requestParam.value();
                String value = req.getParameter(name);
                if (value == null) {
                    if (requestParam.required()) {
                        throw new IllegalArgumentException("Missing required parameter '" + name + "'");
                    }
                    params[i] = null;
                } else if (parameterType == String.class) {
                    params[i] = value;
                } else if (parameterType == int.class || parameterType == Integer.class) {
                    params[i] = Integer.parseInt(value);
                } else if (parameterType == long.class || parameterType == Long.class) {
                    params[i] = Long.parseLong(value);
                } else if (parameterType == boolean.class || parameterType == Boolean.class) {
                    params[i] = Boolean.parseBoolean(value);
                } else {
                    throw new RuntimeException("Unknown parameter type " + parameterType);
                }
            } else if ((sessionAttr = getParamAnnotation(method, i, SessionAttr.class)) != null) {
                String name = sessionAttr.value();
                Object value = req.getSession(true).getAttribute(name);
                if (value == null) {
                    if (sessionAttr.required()) {
                        throw new IllegalArgumentException("Missing required session attribute '" + name + "'");
                    }
                    params[i] = null;
                } else if (parameterType.isAssignableFrom(value.getClass())) {
                    params[i] = value;
                } else {
                    throw new ServletException("Session value of type " + value.getClass()
                            + "is not assignalble to parameter " + name + " of type " + parameterType);
                }
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() > 1) {
                throw new ServletException(
                        "Spring context has multiple beans of type " + parameterType.getName());
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() == 1) {
                params[i] = applicationContext.getBeansOfType(parameterType).values().iterator().next();
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() == 0) {
                throw new ServletException("Unknown parameter type " + parameterType.getName());
            } else {
                throw new ServletException("Unknown parameter type " + parameterType.getName());
            }

        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    return params;
}

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

public static boolean isBeanPropertyWriteMethod(Method method) {
    return method != null && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class
            && method.getParameterTypes().length == 1 && method.getName().startsWith("set")
            && method.getName().length() > 3;
}

From source file:de.xaniox.heavyspleef.core.event.EventListenerMethod.java

@SuppressWarnings("unchecked")
public EventListenerMethod(Object instance, Method method) {
    this.instance = instance;
    this.method = method;

    if (!method.isAccessible()) {
        method.setAccessible(true);// ww  w  .ja va  2 s.co m
    }

    subscribe = method.getAnnotation(Subscribe.class);

    Class<?>[] parameters = method.getParameterTypes();
    Validate.isTrue(parameters.length == 1,
            "method must have only one parameter which must be a subtype of Event");

    Class<?> eventClass = parameters[0];
    Validate.isTrue(Event.class.isAssignableFrom(eventClass),
            "First parameter of method must be a subtype of Event");

    this.eventClass = (Class<? extends Event>) eventClass;
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint.java

public void processRequest(Object context, JsonNode requestJson) {
    JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
    request.setMethod(requestJson.get("method").asText());
    logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
    OvsdbRPC.Callback callback = requestCallbacks.get(context);
    if (callback != null) {
        Method[] methods = callback.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(request.getMethod())) {
                Class<?>[] parameters = method.getParameterTypes();
                JsonNode params = requestJson.get("params");
                Object param = objectMapper.convertValue(params, parameters[1]);
                try {
                    Invokable from = Invokable.from(method);
                    from.setAccessible(true);
                    from.invoke(callback, context, param);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    logger.error("Unable to invoke callback " + method.getName(), e);
                }//from  w w  w .  j av a 2  s  .co m
                return;
            }
        }
    }

    // Echo dont need any special processing. hence handling it internally.

    if (request.getMethod().equals("echo")) {
        JsonRpc10Response response = new JsonRpc10Response(request.getId());
        response.setError(null);
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(response);
            nettyChannel.writeAndFlush(jsonString);
        } catch (JsonProcessingException e) {
            logger.error("Exception while processing JSON string " + jsonString, e);
        }
        return;
    }

    logger.error("No handler for Request : {} on {}", requestJson.toString(), context);
}

From source file:org.LexGrid.LexBIG.caCore.client.proxy.LexEVSProxyHelperImpl.java

/**
 * Returns true if the object is initialized
 *//*  ww  w . j av  a2  s  .  c o m*/
@SuppressWarnings("unchecked")
@Override
public boolean isInitialized(MethodInvocation invocation) throws Throwable {
    if (invocation.getThis() == null || invocation.getThis() instanceof RemoteShell) {
        return false;
    }

    Class implClass = invocation.getThis().getClass();

    // LexBig objects have methods that must be executed remotely
    if (LexEVSCaCoreUtils.isLexBigClass(implClass)) {
        Method method = invocation.getMethod();
        Method methodImpl = implClass.getMethod(method.getName(), method.getParameterTypes());

        if (methodImpl.isAnnotationPresent(ADMIN_FUNCTION)) {
            throw new UnsupportedOperationException(
                    "Admin functions cannot be executed using the distributed API");
        }

        if (isClientSafe(methodImpl)) {
            log.info("DLB calling locally: " + implClass.getName() + "." + methodImpl.getName());
            return true;
        }

        log.info("DLB calling remotely: " + implClass.getName() + "." + methodImpl.getName());
        return false;
    }

    return true;
}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

FactoryBean getServiceProperty(OsgiServiceCollectionProxyFactoryBean pfb, ServiceReference s,
        Method writeMethod, String beanName) throws Exception {
    Class<?>[] params = writeMethod.getParameterTypes();
    if (SortedSet.class.isAssignableFrom(params[0])) {
        pfb.setCollectionType(CollectionType.SORTED_SET);
    } else if (Set.class.isAssignableFrom(params[0])) {
        pfb.setCollectionType(CollectionType.SET);
    } else if (List.class.isAssignableFrom(params[0])) {
        pfb.setCollectionType(CollectionType.LIST);
    } else {//  w w  w.j  a v  a2s. co m
        throw new IllegalArgumentException(
                "Setter for [" + beanName + "] does not have a valid Collection type argument");
    }
    return getServicePropertyInternal(pfb, s, writeMethod, beanName);
}