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:io.dyn.core.handler.AnnotationHandlerMethodResolver.java

@Override
public Map<Object, HandlerMethod> resolve(Class<?> aClass, Object... args) {
    final Map<Object, HandlerMethod> handlerMethods = new HashMap<>();
    //log.debug("Finding handler methods in %s", aClass);
    Class<?> clazz = aClass;
    while (null != clazz && clazz != Object.class) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override/* w w w. j  a  v  a 2 s  .c o  m*/
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

                Class<?>[] paramTypes = method.getParameterTypes();
                String[] paramNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
                HandlerMethodArgument[] handlerMethodArgs = new HandlerMethodArgument[paramTypes.length];
                Annotation[][] paramAnnos = method.getParameterAnnotations();
                Expression[] valueExpressions = new Expression[paramTypes.length];
                for (int i = 0; i < paramTypes.length; i++) {
                    String paramName = (null != paramNames ? paramNames[i] : "arg" + i);
                    if (paramAnnos[i].length > 0) {
                        for (int j = 0; j < paramAnnos[i].length; j++) {
                            if (paramAnnos[i][j] instanceof Value) {
                                valueExpressions[i] = SpelExpression.DEFAULT_PARSER
                                        .parseExpression(((Value) paramAnnos[i][j]).value());
                                break;
                            }
                        }
                    }
                    handlerMethodArgs[i] = new HandlerMethodArgument(i, paramName, paramTypes[i],
                            valueExpressions[i]);
                }

                Guard guard = null;
                When when = Handlers.find(When.class, method);
                if (null != when) {
                    guard = new Guard(SpelExpression.DEFAULT_PARSER.parseExpression(when.value()));
                }

                On on = Handlers.find(On.class, method);
                String eventName = Handlers.findEventName(method);
                if (null != eventName) {
                    Object key = eventName;
                    if (eventName.contains("#{")) {
                        key = SpelExpression.DEFAULT_PARSER.parseExpression(eventName,
                                ParserContext.TEMPLATE_EXPRESSION);
                    }
                    handlerMethods.put(key, new HandlerMethod(method, handlerMethodArgs, guard));

                }
            }
        }, Handlers.USER_METHODS);
        clazz = clazz.getSuperclass();
    }
    return (handlerMethods.size() > 0 ? handlerMethods : null);
}

From source file:com.netflix.hystrix.contrib.javanica.utils.MethodProvider.java

/**
 * Gets method by name and parameters types using reflection,
 * if the given type doesn't contain required method then continue applying this method for all super classes up to Object class.
 *
 * @param type           the type to search method
 * @param name           the method name
 * @param parameterTypes the parameters types
 * @return Some if method exists otherwise None
 *///from   w  ww .  j a v a2  s  . c  o  m
public Optional<Method> getMethod(Class<?> type, String name, Class<?>... parameterTypes) {
    Method[] methods = type.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(name) && Arrays.equals(method.getParameterTypes(), parameterTypes)) {
            return Optional.of(method);
        }
    }
    Class<?> superClass = type.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)) {
        return getMethod(superClass, name, parameterTypes);
    } else {
        return Optional.absent();
    }
}

From source file:org.resthub.rpc.AMQPProxy.java

/**
 * Handles the object invocation.//from ww w  .  j a  v a 2s  .com
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        AMQPProxy handler = (AMQPProxy) Proxy.getInvocationHandler(value);

        return _factory.equals(handler._factory);
    } else if (methodName.equals("hashCode") && params.length == 0) {
        return _factory.hashCode();
    } else if (methodName.equals("toString") && params.length == 0) {
        return "[HessianProxy " + proxy.getClass() + "]";
    }

    ConnectionFactory connectionFactory = _factory.getConnectionFactory();

    Message response = sendRequest(connectionFactory, method, args);

    if (response == null) {
        throw new TimeoutException();
    }

    MessageProperties props = response.getMessageProperties();
    boolean compressed = "deflate".equals(props.getContentEncoding());

    InputStream is = new ByteArrayInputStream(response.getBody());
    if (compressed) {
        is = new InflaterInputStream(is, new Inflater(true));
    }

    return _factory.getSerializationHandler().readObject(method.getReturnType(), is);
}

From source file:kenh.expl.impl.BaseFunction.java

/**
 * Find the method with name <code>process</code> or <code>@Processing</code>
 *//*from  w w w  .  j  a va 2s .com*/
@Override
public Object invoke(Object... params) throws UnsupportedExpressionException {
    Method[] methods = this.getClass().getMethods();

    for (Method method : methods) {
        String name = method.getName();
        Class[] classes = method.getParameterTypes();
        Annotation a = method.getAnnotation(Processing.class);

        if ((name.equals(METHOD) || a != null) && params.length == classes.length) {

            logger.trace("Method: " + method.toGenericString());
            boolean find = true;
            Object[] objs = new Object[params.length];
            for (int i = 0; i < params.length; i++) {
                Class class1 = params[i].getClass();
                Class class2 = classes[i];

                if (class2.isAssignableFrom(class1) || class2 == Object.class) {
                    objs[i] = params[i];

                } else if (class1 == String.class) {
                    try {
                        Object obj = Environment.convert((String) params[i], class2);
                        if (obj == null) {
                            logger.trace("Failure(Convert failure[" + (i + 1) + "-" + class1 + "," + class2
                                    + "]): " + method.toGenericString());
                            find = false;
                            break;
                        } else {
                            objs[i] = obj;
                        }
                    } catch (Exception e) {
                        logger.trace("Failure(Convert exception[" + (i + 1) + "-" + e.getMessage() + "]): "
                                + method.toGenericString());
                        find = false;
                        break;
                        //UnsupportedExpressionException ex = new UnsupportedExpressionException(e);
                        //throw ex;
                    }
                } else {
                    logger.trace("Failure(Class unmatched[" + (i + 1) + "]): " + method.toGenericString());
                    find = false;
                    break;
                }
            }
            if (find) {
                try {
                    return method.invoke(this, objs);
                } catch (Exception e) {
                    if (e instanceof UnsupportedExpressionException)
                        throw (UnsupportedExpressionException) e;
                    else
                        throw new UnsupportedExpressionException(e);
                }
            }
        }
    }

    String paramStr = "";
    for (Object param : params) {
        paramStr += param.getClass().getCanonicalName() + ", ";
    }
    paramStr = StringUtils.defaultIfBlank(StringUtils.chop(StringUtils.trimToEmpty(paramStr)), "<NO PARAM>");

    UnsupportedExpressionException e = new UnsupportedExpressionException(
            "Can't find the method to process.[" + paramStr + "]");
    throw e;
}

From source file:com.bstek.dorado.view.resolver.VelocityInterceptorDirective.java

@SuppressWarnings("rawtypes")
protected void intercept(InternalContextAdapter contextAdapter, Writer writer, Node node) throws Exception {
    int paramNum = node.jjtGetNumChildren();
    if (paramNum == 0) {
        throw new IllegalArgumentException("No interceptor name defined in #interceptor.");
    }//from   w w  w.  j av  a2 s . c  o m
    String interceptorName = (String) node.jjtGetChild(0).value(contextAdapter);
    if (StringUtils.isEmpty(interceptorName)) {
        throw new IllegalArgumentException("The interceptor name defined in #interceptor can not be empty.");
    }
    if (interceptorName.indexOf('#') <= 0) {
        throw new IllegalArgumentException("Invalid interceptor name [" + interceptorName + "].");
    }
    String beanName = StringUtils.substringBefore(interceptorName, "#");
    String methodName = StringUtils.substringAfter(interceptorName, "#");
    if (StringUtils.isEmpty(methodName)) {
        throw new IllegalArgumentException("Invalid interceptor name [" + interceptorName + "].");
    }

    if (paramNum > 2) {
        throw new IllegalArgumentException("Too more arguments defined in #interceptor.");
    }

    Map parameterMap = null;
    if (paramNum == 2) {
        parameterMap = (Map) node.jjtGetChild(1).value(contextAdapter);
    }

    Object bean = BeanFactoryUtils.getBean(beanName);
    Method[] methods = MethodAutoMatchingUtils.getMethodsByName(bean.getClass(), methodName);
    if (methods.length == 0) {
        throw new IllegalArgumentException("No method found for [" + interceptorName + "].");
    } else if (methods.length > 1) {
        throw new IllegalArgumentException("More than one method found for [" + interceptorName + "].");
    }
    Method method = methods[0];
    View view = (View) contextAdapter.get("view");

    Class<?>[] parameterTypes = method.getParameterTypes();
    String[] parameterNames = MethodAutoMatchingUtils.getParameterNames(method);
    Object[] parameters = new Object[parameterTypes.length];
    int i = 0;
    for (Class<?> parameterType : parameterTypes) {
        if (Writer.class.isAssignableFrom(parameterType)) {
            /* Writer */
            parameters[i] = writer;
        } else if (Context.class.isAssignableFrom(parameterType)) {
            /* Velocity Context */
            parameters[i] = contextAdapter;
        } else if (ViewElement.class.isAssignableFrom(parameterType)) {
            /* Component or View */
            String parameterName = parameterNames[i];
            if ("view".equals(parameterName)) {
                parameters[i] = view;
            } else {
                parameters[i] = view.getViewElement(parameterName);
            }
        } else if (parameterMap != null) {
            /* from ParameterMap */
            String parameterName = parameterNames[i];
            parameters[i] = parameterMap.get(parameterName);
        }
        i++;
    }

    method.invoke(bean, parameters);
}

From source file:com.medallia.tiny.ObjectProvider.java

/**
 * Creates a parameter list for invoking the method using object from this ObjectProvider.
 * Parameters are obtained by calling {@link #get(Class)} on the classes in m.getParameterTypes().
 * If a lastArg is specified for this ObjectProvider, the last argument will be that object.
 *///w w  w. j  av a  2 s .  c om
public Object[] makeArgsFor(Method m) {
    Class<?>[] pt = m.getParameterTypes();
    Annotation[][] a = m.getParameterAnnotations();
    return makeArgsFor(pt, a);
}

From source file:com.all.appControl.RequestMethodHandler.java

public RequestMethodHandler(Object object, Method method) {
    super(object, method);
    if (method.getParameterTypes().length > 1) {
        throw new IllegalMethodException(
                "Illegal Engine binding on: " + object.getClass().getName() + "." + method.getName());
    }/*from  w  w  w  .j  ava 2s.  c o m*/
}

From source file:org.bytesoft.openjtcc.supports.dubbo.internal.RemoteInvocationEndpointSelector.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Method handlerMethod = null;/*from  ww w  . j a v  a2  s .  c om*/
    try {
        handlerMethod = RemoteInvocationEndpointSelector.class.getDeclaredMethod(method.getName(),
                method.getParameterTypes());
        return handlerMethod.invoke(this, args);
    } catch (Exception ex) {
        RemoteInvocationService delegate = this.getRemoteInvocationService();
        return method.invoke(delegate, args);
    }
}

From source file:de.openknowledge.extensions.jsf.model.ModelMethod.java

private Method findMethod(Class<?> type, String name, Class<?>[] parameters) {
    for (Method method : type.getMethods()) {
        if (method.getName().equals(name)) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length != parameters.length) {
                continue;
            }/*from  ww  w . ja v  a  2s.co  m*/
            boolean match = true;
            for (int i = 0; i < parameters.length; i++) {
                if (parameters[i] != null && !parameterTypes[i].isAssignableFrom(parameters[i])) {
                    match = false;
                    break;
                }
            }
            if (match) {
                // TODO currently we simply take the first match... We should resolve based on java resolution rules...
                return method;
            }
        }
    }
    throw new ELException("method with name '" + name + "' not found in type " + type.getName());
}

From source file:ProxyAdapter.java

@SuppressWarnings("unchecked")
public ProxyAdapter(Class... interfaces) {
    proxy = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Method m;//  www  .  ja  va 2  s.co m
            try {
                //Determine if the method has been defined in a subclass
                m = ProxyAdapter.this.getClass().getMethod(method.getName(), method.getParameterTypes());
                m.setAccessible(true);
            } catch (Exception e) { //if not found
                throw new UnsupportedOperationException(method.toString(), e);

            }
            //Invoke the method found and return the result
            try {
                return m.invoke(ProxyAdapter.this, args);
            } catch (InvocationTargetException e) {
                throw e.getCause();
            }
        }
    });
}