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.asual.summer.core.util.ClassUtils.java

public static Object invokeMethod(Object target, final String methodName, final Object[] parameters) {
    if (target != null) {
        final List<Method> matches = new ArrayList<Method>();
        ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                matches.add(method);//from  w w w .  j ava  2s  .  c  om
            }
        }, new ReflectionUtils.MethodFilter() {
            public boolean matches(Method method) {
                if (method.getName().equals(methodName)) {
                    Class<?>[] types = method.getParameterTypes();
                    if (parameters == null && types.length == 0) {
                        return true;
                    }
                    if (types.length != parameters.length) {
                        return false;
                    }
                    for (int i = 0; i < types.length; i++) {
                        if (!types[i].isInstance(parameters[i])) {
                            return false;
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        if (matches.size() > 0) {
            if (parameters == null) {
                return ReflectionUtils.invokeMethod(matches.get(0), target);
            } else {
                return ReflectionUtils.invokeMethod(matches.get(0), target, parameters);
            }
        }
    }
    return null;
}

From source file:com.haulmont.cuba.core.config.ConfigUtil.java

/**
 * Get the type of a method. If the method has a non-void return
 * type, that type is returned. Otherwise if the method has at least
 * one parameter, the type of the first parameter is returned.
 *
 * @param method The method.//from   w w  w .j  av a 2 s. co  m
 * @return The method type, or else {@link Void#TYPE}.
 */
public static Class<?> getMethodType(Method method) {
    Class<?> methodType = method.getReturnType();
    if (Void.TYPE.equals(methodType)) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length > 0) {
            methodType = parameterTypes[0];
        }
    }
    return methodType;
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * TODO: provide support for nested JSON objects
 * TODO: provide support for embedded JSON Arrays
 *
 * @param jsonObject//from   w ww . j a  va 2  s.c  om
 * @param beanToBeCreatedClass
 * @param <T>
 * @return
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws JSONException
 * @throws NoSuchMethodException
 * @throws java.lang.reflect.InvocationTargetException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass)
        throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException,
        InvocationTargetException {
    T value = beanToBeCreatedClass.getConstructor().newInstance();

    Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object field = jsonObject.get(key);

        //  capitalise to standard setter pattern
        String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1);

        //System.err.println("method name:" + methodName);

        Method method = getCandidateMethod(beanToBeCreatedClass, methodName);

        if (method != null) {
            Class clazz = method.getParameterTypes()[0];

            // discriminate based on type
            if (field.equals(JSONObject.NULL)) {
                method.invoke(value, clazz.cast(null));
            } else if (field instanceof String) {
                // check if we're an enum
                if (clazz.isEnum()) {
                    Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field);
                    try {
                        beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm);
                        continue;
                    } catch (NoSuchMethodException e) {
                        // that means there was no such method, proceed
                    }
                }

                // string shall be used directly, either to set or as constructor parameter (if suitable)
                try {
                    beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field);
                    continue;
                } catch (NoSuchMethodException e) {
                    // that means there was no such method, proceed
                }
                // or maybe there is method with suitable parameter?
                if (clazz.isPrimitive() && primitves.get(clazz) != null) {
                    clazz = primitves.get(clazz);
                }
                try {
                    method.invoke(value, clazz.getConstructor(String.class).newInstance(field));
                } catch (NoSuchMethodException nsme) {
                    // we are failed here,  but so what? be lenient
                }

            }
            // we are done with string
            else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) {
                // JSON array corresponds either to array type, or to some collection
                if (field instanceof JSONObject) {
                    JSONArray array = new JSONArray();
                    array.put(field);
                    field = array;
                }

                // we are interested in arrays for now
                if (clazz.isArray()) {
                    // populate field value from JSON Array
                    Object fieldValue = populateRecursive(clazz, field);
                    method.invoke(value, fieldValue);
                } else if (clazz.isAssignableFrom(List.class)) {
                    try {
                        Type type = method.getGenericParameterTypes()[0];
                        if (type instanceof ParameterizedType) {
                            Type param = ((ParameterizedType) type).getActualTypeArguments()[0];
                            if (param instanceof Class) {
                                Class c = (Class) param;

                                // populate field value from JSON Array
                                Object fieldValue = populateRecursiveList(clazz, c, field);
                                method.invoke(value, fieldValue);
                            }
                        }
                    } catch (Exception e) {
                        // failed
                    }
                }

            } else if (field instanceof JSONObject) {
                // JSON object means nested bean - process recursively
                method.invoke(value, unmarshall((JSONObject) field, clazz));
            } else if (clazz.equals(Date.class)) {
                method.invoke(value, new Date((Long) field));
            } else {

                // fallback here,  types not yet processed will be
                // set directly ( if possible )
                // TODO: guard this? for better leniency
                method.invoke(value, field);
            }

        }
    }
    return value;
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition.java

/**
 * Get a list of methods, excluding overloaded ones, biased towards the method with the least number of arguments
 * (in other words, if a method is overloaded, the instance with the fewest arguments is included in the return
 * value).//from w w w  . j a  v  a 2s  .  c om
 * 
 * @param allMethods
 * @return
 */
public static Collection<Method> filterOverloadedMethods(List<Method> allMethods) {

    Map<String, Method> methodsMap = new HashMap<String, Method>();
    for (Method method : allMethods) {
        if (methodsMap.containsKey(method.getName())) {
            if (methodsMap.get(method.getName()).getParameterTypes().length > method
                    .getParameterTypes().length) {
                methodsMap.put(method.getName(), method);
            }
        } else {
            methodsMap.put(method.getName(), method);
        }
    }

    return methodsMap.values();
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

public static boolean getProperties(Object target, Map<String, Object> props, String optionPrefix) {

    boolean rc = false;
    if (target == null) {
        throw new IllegalArgumentException("target was null.");
    }//from   w ww.  j a va2s  .  c o  m
    if (props == null) {
        throw new IllegalArgumentException("props was null.");
    }

    if (optionPrefix == null) {
        optionPrefix = "";
    }

    Class<?> clazz = target.getClass();
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        String name = method.getName();
        Class<?> type = method.getReturnType();
        Class<?> params[] = method.getParameterTypes();
        if ((name.startsWith("is") || name.startsWith("get")) && params.length == 0 && type != null
                && isSettableType(type)) {

            try {

                Object value = method.invoke(target, new Object[] {});
                if (value == null) {
                    continue;
                }

                String strValue = convertToString(value, type);
                if (strValue == null) {
                    continue;
                }
                if (name.startsWith("get")) {
                    name = name.substring(3, 4).toLowerCase() + name.substring(4);
                } else {
                    name = name.substring(2, 3).toLowerCase() + name.substring(3);
                }
                props.put(optionPrefix + name, strValue);
                rc = true;

            } catch (Throwable ignore) {
            }

        }
    }

    return rc;
}

From source file:Main.java

/**
 * <p>// w  w w. j  av a 2s. co  m
 * Register a VTI.
 * </p>
 */
public static void registerVTI(Method method, String[] columnNames, String[] columnTypes, boolean readsSqlData)
        throws Exception {
    String methodName = method.getName();
    String sqlName = doubleQuote(methodName);
    Class methodClass = method.getDeclaringClass();
    Class[] parameterTypes = method.getParameterTypes();
    int parameterCount = parameterTypes.length;
    int columnCount = columnNames.length;
    StringBuilder buffer = new StringBuilder();

    buffer.append("create function ");
    buffer.append(sqlName);
    buffer.append("\n( ");
    for (int i = 0; i < parameterCount; i++) {
        if (i > 0) {
            buffer.append(", ");
        }

        String parameterType = mapType(parameterTypes[i]);

        buffer.append("arg");
        buffer.append(i);
        buffer.append(" ");
        buffer.append(parameterType);
    }
    buffer.append(" )\n");

    buffer.append("returns table\n");
    buffer.append("( ");
    for (int i = 0; i < columnCount; i++) {
        if (i > 0) {
            buffer.append(", ");
        }

        buffer.append("\"" + columnNames[i] + "\"");
        buffer.append(" ");
        buffer.append(columnTypes[i]);
    }
    buffer.append(" )\n");

    buffer.append("language java\n");
    buffer.append("parameter style DERBY_JDBC_RESULT_SET\n");
    if (readsSqlData) {
        buffer.append("reads sql data\n");
    } else {
        buffer.append("no sql\n");
    }

    buffer.append("external name ");
    buffer.append("'");
    buffer.append(methodClass.getName());
    buffer.append(".");
    buffer.append(methodName);
    buffer.append("'\n");

    executeDDL(buffer.toString());
}

From source file:com.jetyun.pgcd.rpc.reflect.ClassAnalyzer.java

/**
 * Analyze a class and create a ClassData object containing all of the
 * public methods (both static and non-static) in the class.
 * //from  w w w.ja va2s .c  om
 * @param clazz
 *            class to be analyzed.
 * 
 * @return a ClassData object containing all the public static and
 *         non-static methods that can be invoked on the class.
 */
private static ClassData analyzeClass(Class clazz) {
    log.info("analyzing " + clazz.getName());
    Method methods[] = clazz.getMethods();
    ClassData cd = new ClassData();
    cd.clazz = clazz;

    // Create temporary method map
    HashMap staticMethodMap = new HashMap();
    HashMap methodMap = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getDeclaringClass() == Object.class) {
            continue;
        }
        int mod = methods[i].getModifiers();
        if (!Modifier.isPublic(mod)) {
            continue;
        }
        Class param[] = method.getParameterTypes();

        // don't count locally resolved args
        int argCount = 0;
        for (int n = 0; n < param.length; n++) {
            if (LocalArgController.isLocalArg(param[n])) {
                continue;
            }
            argCount++;
        }

        MethodKey mk = new MethodKey(method.getName(), argCount);
        ArrayList marr = (ArrayList) methodMap.get(mk);
        if (marr == null) {
            marr = new ArrayList();
            methodMap.put(mk, marr);
        }
        marr.add(method);
        if (Modifier.isStatic(mod)) {
            marr = (ArrayList) staticMethodMap.get(mk);
            if (marr == null) {
                marr = new ArrayList();
                staticMethodMap.put(mk, marr);
            }
            marr.add(method);
        }
    }
    cd.methodMap = new HashMap();
    cd.staticMethodMap = new HashMap();
    // Convert ArrayLists to arrays
    Iterator i = methodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.methodMap.put(mk, marr.get(0));
        } else {
            cd.methodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    i = staticMethodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.staticMethodMap.put(mk, marr.get(0));
        } else {
            cd.staticMethodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    return cd;
}

From source file:com.palantir.ptoss.cinch.core.BindingContext.java

private static List<ObjectFieldMethod> getParameterlessMethods(Object object, Field field) {
    List<ObjectFieldMethod> methods = Lists.newArrayList();
    for (Method method : field.getType().getDeclaredMethods()) {
        if (method.getParameterTypes().length == 0 && Reflections.isMethodPublic(method)) {
            methods.add(new ObjectFieldMethod(object, field, method));
        }/*from  ww w  .j  a  v  a 2  s  .  com*/
    }
    return methods;
}

From source file:org.synyx.hades.util.ClassUtils.java

/**
 * Checks the given method's parameters to match the ones of the given base
 * class method. Matches generic arguments agains the ones bound in the
 * given DAO interface./*from w  w w .j  a v  a  2  s .  c o m*/
 * 
 * @param method
 * @param baseClassMethod
 * @param daoInterface
 * @return
 */
private static boolean parametersMatch(Method method, Method baseClassMethod, Class<?> daoInterface) {

    Type[] genericTypes = baseClassMethod.getGenericParameterTypes();
    Class<?>[] types = baseClassMethod.getParameterTypes();
    Class<?>[] methodParameters = method.getParameterTypes();

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

        Type type = genericTypes[i];

        if (type instanceof TypeVariable<?>) {

            String name = ((TypeVariable<?>) type).getName();

            if (!matchesGenericType(name, methodParameters[i], daoInterface)) {
                return false;
            }

        } else {

            if (!types[i].equals(methodParameters[i])) {
                return false;
            }
        }
    }

    return true;
}

From source file:net.sf.morph.reflect.support.MethodHolder.java

/**
 * Generate a String description of a Method.
 * @param method//from   w  w  w.  jav a  2s . c o  m
 * @return String
 */
protected static String methodToString(Method method) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<");
    buffer.append(method.getReturnType() == null ? "void" : method.getReturnType().getName());
    buffer.append("> ");
    buffer.append(method.getName());
    buffer.append("(");
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes != null) {
        for (int i = 0; i < parameterTypes.length; i++) {
            buffer.append(parameterTypes[i].getName());
            if (i != parameterTypes.length - 1) {
                buffer.append(",");
            }
        }
    }
    buffer.append(")");
    return buffer.toString();
}