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:it.sample.parser.util.CommonsUtil.java

/**
 * metodo di utilita' per controllare che un metodo sia un getter
 * //from   w  w  w.  ja v  a  2 s  .c o m
 * @param method
 * @return true se il metodo e' un getter, false altrimenti
 */
private static boolean isGetter(Method method) {
    if (!method.getName().startsWith("get"))
        return false;
    if (method.getParameterTypes().length != 0)
        return false;
    if (void.class.equals(method.getReturnType()))
        return false;
    return true;
}

From source file:Main.java

public static List<Method> findAnnotatedMethods(final Class<?> type,
        final Class<? extends Annotation> annotation) {
    final List<Method> methods = new ArrayList<>();
    Method[] ms = type.getDeclaredMethods();
    for (Method method : ms) {
        // Must not static
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }//from  w w w . j av a  2 s  .co m
        // Must be public
        if (Modifier.isPublic(method.getModifiers())) {
            continue;
        }
        // Must has only one parameter
        if (method.getParameterTypes().length != 1) {
            continue;
        }
        // Must has annotation
        if (!method.isAnnotationPresent(annotation)) {
            continue;
        }
        methods.add(method);
    }
    return methods;
}

From source file:de.micromata.genome.tpsb.GroovyExceptionInterceptor.java

protected static String renderMethodBlock(Map<String, Method> collectedMethods) {
    StringBuilder sb = new StringBuilder();
    for (String methn : collectedMethods.keySet()) {

        Method m = collectedMethods.get(methn);

        sb.append("  ").append(methn).append("{\n")//
                .append("    return wrappExpectedEx( { target.").append(m.getName()).append("(");
        for (int i = 0; i < m.getParameterTypes().length; ++i) {
            if (i > 0) {
                sb.append(", ");
            }//from w w w .  j a v  a  2  s.c  om
            sb.append("arg").append(i);
        }
        sb.append(");");
        sb.append("} );\n  }\n");
    }
    return sb.toString();
}

From source file:com.qmetry.qaf.automation.testng.pro.DataProviderUtil.java

/**
 * <p>//  ww  w  .j  a v  a  2 s  .co m
 * Use as TestNG dataProvider.
 * <p>
 * data-provider name: <code>isfw-excel-table</code>
 * <p>
 * provides data from excel sheet marked with data set name<br>
 * Required properties:
 * <ol>
 * <li>test.&lt;method name&gt;.datafile=&lt;datafile URL&gt;,&lt;data set
 * name&gt;,&lt;optional sheet name&gt; If the data is not in in first sheet
 * of workbook then provide sheet-name with datafile separated by comma
 * </ol>
 * 
 * @param m
 * @return
 */
@DataProvider(name = "isfw_excel_table")
public static Object[][] getExcelTableData(Method m) {
    Map<String, String> param = getParameters(m);

    Class<?> types[] = m.getParameterTypes();
    if ((types.length == 1) && Map.class.isAssignableFrom(types[0])) {
        // will consider first row as header row
        return ExcelUtil.getTableDataAsMap(param.get(params.DATAFILE.name()), (param.get(params.KEY.name())),
                param.get(params.SHEETNAME.name()));
    }
    return ExcelUtil.getTableData(param.get(params.DATAFILE.name()), (param.get(params.KEY.name())),
            param.get(params.SHEETNAME.name()));
}

From source file:edu.cornell.mannlib.vedit.util.OperationUtils.java

/**
 * Takes a bean and clones it using reflection. Any fields without standard
 * getter/setter methods will not be copied.
 *//*  ww  w . j  a  v  a2s  .c  o m*/
public static Object cloneBean(final Object bean, final Class<?> beanClass, final Class<?> iface) {
    if (bean == null) {
        throw new NullPointerException("bean may not be null.");
    }
    if (beanClass == null) {
        throw new NullPointerException("beanClass may not be null.");
    }
    if (iface == null) {
        throw new NullPointerException("iface may not be null.");
    }

    class CloneBeanException extends RuntimeException {
        public CloneBeanException(String message, Throwable cause) {
            super(message + " <" + cause.getClass().getSimpleName() + ">: bean=" + bean + ", beanClass="
                    + beanClass.getName() + ", iface=" + iface.getName(), cause);
        }
    }

    Object newBean;
    try {
        newBean = beanClass.getConstructor().newInstance();
    } catch (NoSuchMethodException e) {
        throw new CloneBeanException("bean has no 'nullary' constructor.", e);
    } catch (InstantiationException e) {
        throw new CloneBeanException("tried to create instance of an abstract class.", e);
    } catch (IllegalAccessException e) {
        throw new CloneBeanException("bean constructor is not accessible.", e);
    } catch (InvocationTargetException e) {
        throw new CloneBeanException("bean constructor threw an exception.", e);
    } catch (Exception e) {
        throw new CloneBeanException("failed to instantiate a new bean.", e);
    }

    for (Method beanMeth : iface.getMethods()) {
        String methName = beanMeth.getName();
        if (!methName.startsWith("get")) {
            continue;
        }
        if (beanMeth.getParameterTypes().length != 0) {
            continue;
        }
        String fieldName = methName.substring(3, methName.length());
        Class<?> returnType = beanMeth.getReturnType();

        Method setterMethod;
        try {
            setterMethod = iface.getMethod("set" + fieldName, returnType);
        } catch (NoSuchMethodException nsme) {
            continue;
        }

        Object fieldVal;
        try {
            fieldVal = beanMeth.invoke(bean, (Object[]) null);
        } catch (Exception e) {
            throw new CloneBeanException("failed to invoke " + beanMeth, e);
        }

        try {
            Object[] setArgs = new Object[1];
            setArgs[0] = fieldVal;
            setterMethod.invoke(newBean, setArgs);
        } catch (Exception e) {
            throw new CloneBeanException("failed to invoke " + setterMethod, e);
        }
    }
    return newBean;
}

From source file:com.weibo.api.motan.protocol.grpc.GrpcUtil.java

@SuppressWarnings("rawtypes")
public static HashMap<String, MethodDescriptor> getMethodDescriptorByAnnotation(Class<?> clazz,
        String serialization) throws Exception {
    String clazzName = getGrpcClassName(clazz);
    HashMap<String, MethodDescriptor> result = serviceMap.get(clazzName);
    if (result == null) {
        synchronized (serviceMap) {
            if (!serviceMap.containsKey(clazzName)) {
                ServiceDescriptor serviceDesc = getServiceDesc(getGrpcClassName(clazz));
                HashMap<String, MethodDescriptor> methodMap = new HashMap<String, MethodDescriptor>();
                for (MethodDescriptor<?, ?> methodDesc : serviceDesc.getMethods()) {
                    Method interfaceMethod = getMethod(methodDesc.getFullMethodName(), clazz);
                    if (JSON_CODEC.equals(serialization)) {
                        methodDesc = convertJsonDescriptor(methodDesc, interfaceMethod.getParameterTypes()[0],
                                interfaceMethod.getReturnType());
                    }//from  w w w .j  a v a 2 s  .  com
                    methodMap.put(interfaceMethod.getName(), methodDesc);
                }
                serviceMap.put(clazzName, methodMap);
            }
            result = serviceMap.get(clazzName);
        }
    }
    return result;
}

From source file:it.unibo.alchemist.language.protelis.util.ReflectionUtils.java

private static Method loadBestMethod(final Class<?> clazz, final String methodName, final Class<?>[] argClass) {
    Objects.requireNonNull(clazz, "The class on which the method will be invoked can not be null.");
    Objects.requireNonNull(methodName, "Method name can not be null.");
    Objects.requireNonNull(argClass, "Method arguments can not be null.");
    /*/*from  w  w  w  .j a  v a 2  s . co m*/
     * If there is a matching method, return it
     */
    try {
        return clazz.getMethod(methodName, argClass);
    } catch (NoSuchMethodException | SecurityException e) {
        /*
         * Look it up on the cache
         */
        /*
         * Deal with Java method overloading scoring methods
         */
        final Method[] candidates = clazz.getMethods();
        final List<Pair<Integer, Method>> lm = new ArrayList<>(candidates.length);
        for (final Method m : candidates) {
            // TODO: Workaround for different Method API
            if (m.getParameterTypes().length == argClass.length && methodName.equals(m.getName())) {
                final Class<?>[] params = m.getParameterTypes();
                int p = 0;
                boolean compatible = true;
                for (int i = 0; compatible && i < argClass.length; i++) {
                    final Class<?> expected = params[i];
                    if (expected.isAssignableFrom(argClass[i])) {
                        /*
                         * No downcast required, there is compatibility
                         */
                        p++;
                    } else if (!PrimitiveUtils.classIsNumber(expected)) {
                        compatible = false;
                    }
                }
                if (compatible) {
                    lm.add(new Pair<>(p, m));
                }
            }
        }
        /*
         * Find best
         */
        if (lm.size() > 0) {
            Pair<Integer, Method> max = lm.get(0);
            for (Pair<Integer, Method> cPair : lm) {
                if (cPair.getFirst().compareTo(max.getFirst()) > 0) {
                    max = cPair;
                }
            }
            return max.getSecond();
        }
    }
    List<Class<?>> list = new ArrayList<>();
    for (Class<?> c : argClass) {
        list.add(c);
    }
    final String argType = list.toString();
    throw new NoSuchMethodError(
            methodName + "/" + argClass.length + argType + " does not exist in " + clazz + ".");
}

From source file:com.qmetry.qaf.automation.testng.pro.DataProviderUtil.java

/**
 * <p>// ww  w. ja v  a2s  .  c om
 * Use as TestNG dataProvider.
 * <p>
 * data-provider name: <code>isfw-excel</code>
 * <p>
 * Required properties:
 * <ol>
 * <li>test.&lt;method name&gt;.datafile=&lt;datafile URL&gt;,&lt;optional
 * sheet name&gt; If the data is not in sheet 1 then provide sheet-name with
 * datafile separated by semicolon (;)
 * <li>test.&lt;method name&gt;.data.hasheader=true/false set true to skip
 * header row
 * </ol>
 * 
 * @param m
 * @return
 */

@DataProvider(name = "isfw_excel")
public static Object[][] getExcelData(Method m) {
    Map<String, String> param = getParameters(m);

    Class<?> types[] = m.getParameterTypes();
    if ((types.length == 1) && Map.class.isAssignableFrom(types[0])) {
        // will consider first row as header row
        return ExcelUtil.getExcelDataAsMap(param.get(params.DATAFILE.name()),
                param.get(params.SHEETNAME.name()));
    }
    return ExcelUtil.getExcelData(param.get(params.DATAFILE.name()),
            (param.get(params.HASHEADERROW.name()) != null)
                    && Boolean.valueOf(param.get(params.HASHEADERROW.name())),
            param.get(params.SHEETNAME.name()));
}

From source file:io.rhiot.cloudplatform.service.binding.OperationBinding.java

static OperationBinding operationBinding(PayloadEncoding payloadEncoding, String channel,
        byte[] incomingPayload, Map<String, Object> headers, Registry registry) {
    String rawChannel = channel.substring(channel.lastIndexOf('/') + 1);
    String[] channelParts = rawChannel.split("\\.");
    String service = channelParts[0];
    String operation = channelParts[1];

    List<Object> arguments = new LinkedList<>(asList(channelParts).subList(2, channelParts.length));

    for (Map.Entry<String, Object> header : headers.entrySet()) {
        if (header.getKey().startsWith("RHIOT_ARG")) {
            arguments.add(header.getValue());
        }/* w  ww .j  a  v  a 2  s.com*/
    }

    Object bean = registry.lookupByName(service);
    Validate.notNull(bean, "Cannot find service with name '%s'.", service);
    Class beanType = bean.getClass();

    LOG.debug("Detected service bean type {} for operation: {}", beanType, operation);
    List<Method> beanMethods = new ArrayList<>(asList(beanType.getDeclaredMethods()));
    beanMethods.addAll(asList(beanType.getMethods()));
    Method operationMethod = beanMethods.stream().filter(method -> method.getName().equals(operation)).findAny()
            .get();

    if (incomingPayload != null && incomingPayload.length > 0) {
        Object payload = incomingPayload;
        if (operationMethod.getParameterTypes()[operationMethod.getParameterTypes().length
                - 1] != byte[].class) {
            payload = payloadEncoding.decode(incomingPayload);
        }
        arguments.add(payload);
    }
    return new OperationBinding(service, operation, arguments, operationMethod);
}

From source file:jp.go.nict.langrid.client.soap.io.SoapResponseParser.java

private static <T> T nodeToType(XPathWorkspace w, Node node, Class<T> clazz, Converter converter)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ConversionException, DOMException, ParseException {
    if (clazz.isPrimitive()) {
        return converter.convert(resolveHref(w, node).getTextContent(), clazz);
    } else if (clazz.equals(String.class)) {
        return clazz.cast(resolveHref(w, node).getTextContent());
    } else if (clazz.equals(byte[].class)) {
        try {//  w  w w.ja  v  a 2 s  .  c  o  m
            return clazz.cast(Base64.decodeBase64(resolveHref(w, node).getTextContent().getBytes("ISO8859-1")));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    } else if (clazz.equals(Calendar.class)) {
        Date date = fmt.get().parse(resolveHref(w, node).getTextContent());
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return clazz.cast(c);
    } else if (clazz.isArray()) {
        Class<?> ct = clazz.getComponentType();
        List<Object> elements = new ArrayList<Object>();
        node = resolveHref(w, node);
        for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (!(child instanceof Element))
                continue;
            elements.add(nodeToType(w, child, ct, converter));
        }
        return clazz.cast(elements.toArray((Object[]) Array.newInstance(ct, elements.size())));
    } else {
        T instance = clazz.newInstance();
        node = resolveHref(w, node);
        for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (!(child instanceof Element))
                continue;
            String nn = child.getLocalName();
            Method setter = ClassUtil.findSetter(clazz, nn);
            setter.invoke(instance,
                    nodeToType(w, resolveHref(w, child), setter.getParameterTypes()[0], converter));
        }
        return instance;
    }
}