Example usage for java.lang.reflect Method getParameters

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

Introduction

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

Prototype

public Parameter[] getParameters() 

Source Link

Document

Returns an array of Parameter objects that represent all the parameters to the underlying executable represented by this object.

Usage

From source file:telegram.polling.BotApiProxy.java

@Override
public Object invoke(Object o, Method method, Object[] os) throws Throwable {
    ArrayList<NameValuePair> nvps = new ArrayList<>();
    for (int i = 0; i < method.getParameterCount(); i++) {
        Parameter parameter = method.getParameters()[i];
        if (os[i] != null) {
            String name;//from   w  w  w. j av a2  s .c  o m
            if (parameter.isAnnotationPresent(Param.class)) {
                name = parameter.getDeclaredAnnotation(Param.class).name();
            } else {
                name = parameter.getName();
            }
            nvps.add(new BasicNameValuePair(name, os[i].toString()));
        }
    }
    return callApiMethod(method.getName(), nvps, method.getReturnType());
}

From source file:com.alibaba.dubbo.demo.consumer.DemoAction.java

public DubboBenchmark.BenchmarkMessage prepareArgs() throws InvocationTargetException, IllegalAccessException {

    boolean b = true;
    int i = 100000;
    String s = "??";

    DubboBenchmark.BenchmarkMessage.Builder builder = DubboBenchmark.BenchmarkMessage.newBuilder();

    Method[] methods = builder.getClass().getDeclaredMethods();
    for (Method m : methods) {
        if (m.getName().startsWith("setField") && ((m.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC)) {
            Parameter[] params = m.getParameters();
            if (params.length == 1) {
                String n = params[0].getParameterizedType().getTypeName();
                m.setAccessible(true);/* ww  w . j  av a2s .c o m*/
                if (n.endsWith("java.lang.String")) {
                    m.invoke(builder, new Object[] { s });
                } else if (n.endsWith("int")) {
                    m.invoke(builder, new Object[] { i });
                } else if (n.equals("boolean")) {
                    m.invoke(builder, new Object[] { b });
                }

            }
        }
    }

    return builder.build();

}

From source file:ijfx.ui.widgets.PluginInfoPane.java

private Map<String, Object> convert(Method item) {

    return Maps.newHashMap(ImmutableMap.<String, Object>builder().put("name", item.getName())
            .put("inputs", toList(item.getParameters())).put("output", item.getReturnType().getName()).build());
}

From source file:koper.event.DataEventMessageDispatcher.java

/**
 * ? (?)// w w w  .  j  a v  a2 s. c  om
 *
 * @param method    
 * @param dataEvent ?
 * @return ?(Object[])
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private Object[] getDataEventMethodParameters(Method method, DataEvent dataEvent)
        throws InstantiationException, IllegalAccessException {

    final List<?> args = dataEvent.getArgs();
    final int length = method.getParameters().length;

    Object[] parameters = new Object[length];
    for (int i = 0; i < length; i++) {
        final Parameter parameter = method.getParameters()[i];

        final Class<?> parameterTypeClass = parameter.getType();

        Object o1;
        // ?args?, ?? DataEvent
        if (i == args.size()) {
            o1 = dataEvent;
        } else {
            Object o = args.get(i);

            if (parameterTypeClass.getName().equals(DataEvent.class.getName())) {
                o1 = dataEvent;
            } else {
                o1 = ConverterCenter.convertValue(parameterTypeClass, o);
            }
        }
        parameters[i] = o1;
    }
    return parameters;
}

From source file:com.zhaimi.message.event.DataEventMessageDispatcher.java

/**
 * ? (?)// ww w  .  j a  va 2 s.  c  o m
 *
 * @param method    
 * @param dataEvent ?
 * @return ?(Object[])
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private Object[] getDataEventMethodParameters(Method method, DataEvent dataEvent)
        throws InstantiationException, IllegalAccessException {

    final List<?> args = dataEvent.getArgs();
    final int length = method.getParameters().length;

    Object[] parameters = new Object[length];
    for (int i = 0; i < length; i++) {
        final Parameter parameter = method.getParameters()[i];

        final Class<?> parameterTypeClass = parameter.getType();

        Object o1;
        // ?args?, ?? DataEvent
        if (i == args.size()) {
            o1 = dataEvent;
        } else {
            Object o = args.get(i);

            if (parameterTypeClass.getName().equals("com.zhaimi.message.event.DataEvent")) {
                o1 = dataEvent;
            } else {
                o1 = ConverterCenter.convertValue(parameterTypeClass, o);
            }
        }
        parameters[i] = o1;
    }
    return parameters;
}

From source file:guru.qas.martini.runtime.harness.MartiniCallable.java

protected Object[] getArguments(Step step, Method method, StepImplementation implementation) {
    Parameter[] parameters = method.getParameters();
    Object[] arguments = new Object[parameters.length];

    Map<String, String> exampleValues = null;

    Recipe recipe = martini.getRecipe();
    ScenarioDefinition definition = recipe.getScenarioDefinition();
    if (ScenarioOutline.class.isInstance(definition)) {
        exampleValues = new HashMap<>();
        ScenarioOutline outline = ScenarioOutline.class.cast(definition);

        int exampleLine = recipe.getLocation().getLine();

        List<Examples> examples = outline.getExamples();
        TableRow header = null;/*from   w  w  w .j a v  a 2s. co  m*/
        TableRow match = null;
        for (Iterator<Examples> i = examples.iterator(); null == match && i.hasNext();) {
            Examples nextExamples = i.next();
            List<TableRow> rows = nextExamples.getTableBody();
            for (Iterator<TableRow> j = rows.iterator(); null == match && j.hasNext();) {
                TableRow row = j.next();
                if (row.getLocation().getLine() == exampleLine) {
                    match = row;
                    header = nextExamples.getTableHeader();
                }
            }
        }

        checkState(null != header, "unable to locate matching Examples table");
        List<TableCell> headerCells = header.getCells();
        List<TableCell> rowCells = match.getCells();
        checkState(headerCells.size() == rowCells.size(), "Examples header to row size mismatch");
        for (int i = 0; i < headerCells.size(); i++) {
            String headerValue = headerCells.get(i).getValue();
            String rowValue = rowCells.get(i).getValue();
            exampleValues.put(headerValue, rowValue);
        }
    }

    if (parameters.length > 0) {
        String text = step.getText();
        Pattern pattern = implementation.getPattern();
        Matcher matcher = pattern.matcher(text);
        checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s",
                pattern.pattern(), text);

        int groupCount = matcher.groupCount();
        for (int i = 0; i < groupCount; i++) {
            String parameterAsString = matcher.group(i + 1);
            Parameter parameter = parameters[i];
            Class<?> parameterType = parameter.getType();

            Object converted;
            if (null == exampleValues) {
                converted = conversionService.convert(parameterAsString, parameterType);
            } else {
                Matcher tableMatcher = OUTLINE_PATTERN.matcher(parameterAsString);
                checkState(tableMatcher.find(), "Example table keys must be in the format <key>");
                String key = tableMatcher.group(1);
                String tableValue = exampleValues.get(key);
                converted = conversionService.convert(tableValue, parameterType);
            }

            arguments[i] = converted;
        }
    }

    return arguments;
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {/* www  . ja  v a 2  s .  c  o m*/
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

From source file:koper.event.DataEventMessageDispatcher.java

private void triggerDataEvent(Object listener, String dataObject, MsgBean<String, String> msgBean) {
    if (log.isDebugEnabled())
        log.debug("AbstractDataEventListener??: " + msgBean);

    Class<?> clazz = listener.getClass();

    DataEvent dataEvent = JSON.parseObject(msgBean.getValue(), DefaultDataEvent.class);
    // args : [{"xxx" : xxx, "xxx" : xxx}]
    dataEvent.setTopic(msgBean.getTopic());
    dataEvent.setDataObjectName(dataObject);
    String event = msgBean.getTopic();
    String eventName = getEventName(event);

    dataEvent.setEventName(eventName);//  w w  w  . ja  v  a  2 s  .co m
    dataEvent.setMsgBean(msgBean);

    try {

        if (log.isDebugEnabled())
            log.debug("DataEvent?:{}", event);

        final Optional<Method> methodOptional = ReflectUtil.getMethod(clazz, eventName,
                method -> method.getParameters().length == dataEvent.getArgs().size()
                        || method.getParameters().length == dataEvent.getArgs().size() + 1
                        || method.getParameters().length == 1);
        if (methodOptional.isPresent()) {
            final Method method = methodOptional.get();
            Object[] methodParameters = getDataEventMethodParameters(method, dataEvent);
            ReflectUtil.invoke(listener, method, methodParameters);
        } else {
            log.warn(
                    "Message received! But no event handle method defined {}(DataEvent dataEvent) Message is {}",
                    event, msgBean.getValue());
        }
    } catch (Exception e) {
        log.warn("Fail to call event handle method  {}(DataEvent dataEvent). Message is {}. Exception:{}",
                event, msgBean.getValue(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.zhaimi.message.event.DataEventMessageDispatcher.java

public void triggerDataEvent(Object listener, String dataObject, MsgBean<String, String> msgBean) {
    if (log.isDebugEnabled())
        log.debug("AbstractDataEventListener??: " + msgBean);

    Class<?> clazz = listener.getClass();

    DataEvent dataEvent = JSON.parseObject(msgBean.getValue(), DefaultDataEvent.class);
    // args : [{"xxx" : xxx, "xxx" : xxx}]
    dataEvent.setTopic(msgBean.getTopic());
    dataEvent.setDataObjectName(dataObject);
    String event = msgBean.getTopic();
    String eventName = getEventName(event);

    dataEvent.setEventName(eventName);//from w  w w .j  av  a2  s. c  o  m
    dataEvent.setMsgBean(msgBean);

    try {

        if (log.isDebugEnabled())
            log.debug("DataEvent?:{}", event);

        final Optional<Method> methodOptional = ReflectUtil.getMethod(clazz, eventName,
                method -> method.getParameters().length == dataEvent.getArgs().size()
                        || method.getParameters().length == dataEvent.getArgs().size() + 1
                        || method.getParameters().length == 1);
        if (methodOptional.isPresent()) {
            final Method method = methodOptional.get();
            Object[] methodParameters = getDataEventMethodParameters(method, dataEvent);
            ReflectUtil.invoke(listener, method, methodParameters);
        } else {
            log.warn(
                    "Message received! But no event handle method defined {}(DataEvent dataEvent) Message is {}",
                    event, msgBean.getValue());
        }
    } catch (Exception e) {
        log.warn("Fail to call event handle method  {}(DataEvent dataEvent). Message is {}. Exception:{}",
                event, msgBean.getValue(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.tinkerpop.gremlin.jsr223.JavaTranslator.java

private Object invokeMethod(final Object delegate, final Class returnType, final String methodName,
        final Object... arguments) {
    // populate method cache for fast access to methods in subsequent calls
    final Map<String, List<Method>> methodCache = GLOBAL_METHOD_CACHE.getOrDefault(delegate.getClass(),
            new HashMap<>());
    if (methodCache.isEmpty())
        buildMethodCache(delegate, methodCache);

    // create a copy of the argument array so as not to mutate the original bytecode
    final Object[] argumentsCopy = new Object[arguments.length];
    for (int i = 0; i < arguments.length; i++) {
        argumentsCopy[i] = translateObject(arguments[i]);
    }//w  w w  .  j a  v  a 2  s . co m
    try {
        for (final Method method : methodCache.get(methodName)) {
            if (returnType.isAssignableFrom(method.getReturnType())) {
                if (method.getParameterCount() == argumentsCopy.length || (method.getParameterCount() > 0
                        && method.getParameters()[method.getParameters().length - 1].isVarArgs())) {
                    final Parameter[] parameters = method.getParameters();
                    final Object[] newArguments = new Object[parameters.length];
                    boolean found = true;
                    for (int i = 0; i < parameters.length; i++) {
                        if (parameters[i].isVarArgs()) {
                            final Class<?> parameterClass = parameters[i].getType().getComponentType();
                            if (argumentsCopy.length > i
                                    && !parameterClass.isAssignableFrom(argumentsCopy[i].getClass())) {
                                found = false;
                                break;
                            }
                            Object[] varArgs = (Object[]) Array.newInstance(parameterClass,
                                    argumentsCopy.length - i);
                            int counter = 0;
                            for (int j = i; j < argumentsCopy.length; j++) {
                                varArgs[counter++] = argumentsCopy[j];
                            }
                            newArguments[i] = varArgs;
                            break;
                        } else {
                            if (i < argumentsCopy.length && (parameters[i].getType()
                                    .isAssignableFrom(argumentsCopy[i].getClass())
                                    || (parameters[i].getType().isPrimitive()
                                            && (Number.class.isAssignableFrom(argumentsCopy[i].getClass())
                                                    || argumentsCopy[i].getClass().equals(Boolean.class)
                                                    || argumentsCopy[i].getClass().equals(Byte.class)
                                                    || argumentsCopy[i].getClass().equals(Character.class))))) {
                                newArguments[i] = argumentsCopy[i];
                            } else {
                                found = false;
                                break;
                            }
                        }
                    }
                    if (found) {
                        return 0 == newArguments.length ? method.invoke(delegate)
                                : method.invoke(delegate, newArguments);
                    }
                }
            }
        }
    } catch (final Throwable e) {
        throw new IllegalStateException(
                e.getMessage() + ":" + methodName + "(" + Arrays.toString(argumentsCopy) + ")", e);
    }
    throw new IllegalStateException("Could not locate method: " + delegate.getClass().getSimpleName() + "."
            + methodName + "(" + Arrays.toString(argumentsCopy) + ")");
}