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:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied name
 * and parameter types. Searches all superclasses up to {@code Object}.
 * <p>Returns {@code null} if no {@link Method} can be found.
 * @param clazz the class to introspect/*from www .  j  a va 2s.  co m*/
 * @param name the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods());
        for (Method method : methods) {
            if (name.equals(method.getName())
                    && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.tugo.dt.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {//w  w w  .  ja va  2  s.  co m
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (org.apache.commons.lang.ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

@SuppressWarnings({ "unchecked", "unchecked" })
public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args)
        throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
        IllegalAccessException {//from  w  w  w .jav a2  s  . c  om
    try {
        List<Method> validMethods = new ArrayList<>();

        for (Method method : clazz.getMethods()) {
            Class<?>[] parameterTypes = null;

            if (!method.getName().equals(methodName)) {
                continue;
            }

            parameterTypes = method.getParameterTypes();
            if (method.isVarArgs()) {
                if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) {
                    parameterTypes = null;
                    continue;
                }
            } else {
                if (parameterTypes.length != args.length) {
                    parameterTypes = null;
                    continue;
                }
            }

            if (method.isVarArgs()) {
                boolean matches = false;

                // check non vararg part
                for (int i = 0; i < parameterTypes.length - 1; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                // check rest
                for (int i = parameterTypes.length - 1; i < args.length; i++) {
                    Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType();

                    matches = checkMatch(arrayType, args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            } else {
                boolean matches = true;

                for (int i = 0; i < parameterTypes.length; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            }
        }

        if (!validMethods.isEmpty()) {
            Method method = validMethods.get(0);
            for (int i = 1; i < validMethods.size(); i++) {
                Method targetMethod = validMethods.get(i);

                Class<?>[] currentParams = method.getParameterTypes();
                Class<?>[] targetParams = targetMethod.getParameterTypes();

                if (method.isVarArgs() && targetMethod.isVarArgs()) {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (currentParams[j].isAssignableFrom(targetParams[j])) {
                            method = targetMethod;
                            break;
                        }
                    }
                } else if (method.isVarArgs()) {
                    //usually, non-vararg is more specific method. So we use that
                    method = targetMethod;
                } else if (targetMethod.isVarArgs()) {
                    //do nothing
                } else {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (targetParams[j].isEnum()) { // enum will be handled later
                            method = targetMethod;
                            break;
                        } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method
                            method = targetMethod;
                            break;
                        }
                    }
                }
            }

            method.setAccessible(true);

            for (int i = 0; i < args.length; i++) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) {
                    try {
                        args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]);
                    } catch (IllegalArgumentException ex1) {
                        // Some overloaded methods already has
                        // String to Enum conversion
                        // So just lets see if one exists
                        Class<?>[] types = new Class<?>[args.length];
                        for (int k = 0; k < args.length; k++)
                            types[k] = args[k].getClass();

                        try {
                            Method alternative = clazz.getMethod(methodName, types);
                            return alternative.invoke(obj, args);
                        } catch (NoSuchMethodException ex2) {
                            throw new RuntimeException(
                                    "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i]
                                            + "] or find appropriate method but found nothing. Make sure"
                                            + " that the value [" + args[i]
                                            + "] matches exactly with one of the Enums in [" + parameterTypes[i]
                                            + "] or the method you are looking exists.");
                        }
                    }
                }
            }

            if (method.isVarArgs()) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(),
                        args.length - parameterTypes.length + 1);
                for (int k = 0; k < Array.getLength(varargs); k++) {
                    Array.set(varargs, k, args[parameterTypes.length - 1 + k]);
                }

                Object[] newArgs = new Object[parameterTypes.length];
                for (int k = 0; k < newArgs.length - 1; k++) {
                    newArgs[k] = args[k];
                }
                newArgs[newArgs.length - 1] = varargs;

                args = newArgs;
            }

            return method.invoke(obj, args);
        }

        if (args.length > 0) {
            StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName()));

            for (int i = 1; i < args.length; i++) {
                builder.append(", " + args[i].getClass().getSimpleName());
            }

            throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")");
        } else {
            throw new NoSuchMethodException(methodName + "()");
        }
    } catch (NullPointerException e) {
        StringBuilder builder = new StringBuilder(String.valueOf(args[0]));
        for (int i = 1; i < args.length; i++)
            builder.append("," + String.valueOf(args[i]));
        throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")");
    }
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static List findMutatorMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne && isPublic;
        }// w w  w.j  a  v a 2s  . co  m
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static List findOtherPublicMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return ((startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne) == false) && isPublic;
        }//  www .j a v  a2 s .co m
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

/**
 * Get the method with the given name from the given class, provided that it takes one argument
 * of the provided type./*from w w w  .j a  v  a  2  s .com*/
 * @param cls The class who should have (or inherit) the method
 * @param methodName The name of the method
 * @param argClass If provided, the type of the sole argument to the method. If null, no argument is assumed.
 * @param onlyProtectedAndHigher If true, we will ignore private methods in the superclasses.
 * @return The method if found, otherwise null.
 */
private static Method getMethodFromClass(Class<?> cls, String methodName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {

    Method[] allMethods = cls.getDeclaredMethods();
    for (Method meth : allMethods) {
        if (!meth.getName().equals(methodName))
            continue;

        if (onlyProtectedAndHigher) {
            int modifiers = meth.getModifiers();
            if (Modifier.isPrivate(modifiers))
                continue;
        }

        if (argClass != null) {
            Class<?>[] paramTypes = meth.getParameterTypes();
            if (paramTypes.length != 1)
                continue;

            Class<?> genericType = getGenericType(paramTypes[0]);
            if (!genericType.isAssignableFrom(argClass))
                continue;
        }

        // Note that if we're trying to set a value to null, we obviously cannot check the
        // signature for overloading, and therefore we'll return the first method which takes
        // one parameter. I think that's not that unreasonable, but it could conceivably break
        // if someone does funny things with their bean.

        return meth;
    }

    return null;
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Static method that parses single JSON Object into FoursquareEntity
 * /*from   w  ww  .  j a v a  2 s. c om*/
 * @param clazz entity class
 * @param jsonObject JSON Object
 * @param skipNonExistingFields whether parser should ignore non-existing fields
 * @return entity
 * @throws FoursquareApiException when something unexpected happens
 */
public static FoursquareEntity parseEntity(Class<?> clazz, JSONObject jsonObject, boolean skipNonExistingFields)
        throws FoursquareApiException {
    FoursquareEntity entity = createNewEntity(clazz);

    String[] objectFieldNames = getFieldNames(jsonObject);
    if (objectFieldNames != null) {
        for (String objectFieldName : objectFieldNames) {
            Class<?> fieldClass = getFieldClass(entity.getClass(), objectFieldName);
            if (fieldClass == null) {
                Method setterMethod = getSetterMethod(entity.getClass(), objectFieldName);
                if (setterMethod == null) {
                    if (!skipNonExistingFields) {
                        throw new FoursquareApiException("Could not find field " + objectFieldName + " from "
                                + entity.getClass().getName() + " class");
                    }
                } else {
                    Class<?>[] parameters = setterMethod.getParameterTypes();
                    if (parameters.length == 1) {
                        fieldClass = parameters[0];

                        try {
                            setterMethod.setAccessible(true);
                            setterMethod.invoke(entity,
                                    parseValue(fieldClass, jsonObject, objectFieldName, skipNonExistingFields));
                        } catch (JSONException e) {
                            throw new FoursquareApiException(e);
                        } catch (IllegalArgumentException e) {
                            throw new FoursquareApiException(e);
                        } catch (IllegalAccessException e) {
                            throw new FoursquareApiException(e);
                        } catch (InvocationTargetException e) {
                            throw new FoursquareApiException(e);
                        }
                    } else {
                        throw new FoursquareApiException("Could not find field " + objectFieldName + " from "
                                + entity.getClass().getName() + " class");
                    }
                }
            } else {
                try {
                    setEntityFieldValue(entity, objectFieldName,
                            parseValue(fieldClass, jsonObject, objectFieldName, skipNonExistingFields));
                } catch (JSONException e) {
                    throw new FoursquareApiException(e);
                }
            }
        }
    }

    return entity;
}

From source file:org.thoughtland.xlocation.Util.java

public static Method getMethod(Class<?> clazz, String name, Object[] args) {
    Util.log(null, Log.DEBUG, "Looking for " + name);
    for (Method m : clazz.getDeclaredMethods()) {
        Util.log(null, Log.DEBUG, "Got method " + clazz.getSimpleName() + "." + m.getName() + "( "
                + TextUtils.join(", ", m.getParameterTypes()) + " )");
        if (m.getName().equals(name)) {
            Util.log(null, Log.DEBUG, "  names match!");
            if (args == null)
                return m;
            Class<?>[] params = m.getParameterTypes();
            if (params.length == args.length) {
                Util.log(null, Log.DEBUG, "  params length match!");
                boolean matches = true;
                for (int i = 0; i < params.length; i++) {
                    if (args[i] != null && !params[i].isInstance(args[i])) {
                        Util.log(null, Log.DEBUG, "  param[" + i + "] " + args[i].getClass().getName()
                                + " does not match type " + params[i].getSimpleName());
                        matches = false;
                        break;
                    }//from  w  w  w .ja va2s  .  c  o  m
                }
                if (matches) {
                    Util.log(null, Log.DEBUG, "Found match for " + name);
                    return m;
                }
            }
        }
    }
    return null;
}

From source file:com.espertech.esper.util.MethodResolver.java

/**
* Attempts to find the static or instance method described by the parameters,
* or a method of the same name that will accept the same type of
* parameters.//from www . ja  va2s .  c  om
 * @param declaringClass - the class to search for the method
* @param methodName - the name of the method
* @param paramTypes - the parameter types for the method
 * @param allowInstance - true to allow instance methods as well, false to allow only static method
* @return - the Method object for this method
* @throws EngineNoSuchMethodException if the method could not be found
*/
public static Method resolveMethod(Class declaringClass, String methodName, Class[] paramTypes,
        boolean allowInstance, boolean[] allowEventBeanType, boolean[] allowEventBeanCollType)
        throws EngineNoSuchMethodException {
    // Get all the methods for this class
    Method[] methods = declaringClass.getMethods();

    Method bestMatch = null;
    int bestConversionCount = -1;

    // Examine each method, checking if the signature is compatible
    Method conversionFailedMethod = null;
    for (Method method : methods) {
        // Check the modifiers: we only want public and static, if required
        if (!isPublicAndStatic(method, allowInstance)) {
            continue;
        }

        // Check the name
        if (!method.getName().equals(methodName)) {
            continue;
        }

        // Check the parameter list
        int conversionCount = compareParameterTypesAllowContext(method.getParameterTypes(), paramTypes,
                allowEventBeanType, allowEventBeanCollType, method.getGenericParameterTypes());

        // Parameters don't match
        if (conversionCount == -1) {
            conversionFailedMethod = method;
            continue;
        }

        // Parameters match exactly
        if (conversionCount == 0) {
            bestMatch = method;
            break;
        }

        // No previous match
        if (bestMatch == null) {
            bestMatch = method;
            bestConversionCount = conversionCount;
        } else {
            // Current match is better
            if (conversionCount < bestConversionCount) {
                bestMatch = method;
                bestConversionCount = conversionCount;
            }
        }

    }

    if (bestMatch != null) {
        logWarnBoxedToPrimitiveType(declaringClass, methodName, bestMatch, paramTypes);
        return bestMatch;
    }

    StringBuilder parameters = new StringBuilder();
    if (paramTypes != null && paramTypes.length != 0) {
        String appendString = "";
        for (Object param : paramTypes) {
            parameters.append(appendString);
            if (param == null) {
                parameters.append("(null)");
            } else {
                parameters.append(param.toString());
            }
            appendString = ", ";
        }
    }
    throw new EngineNoSuchMethodException(
            "Unknown method " + declaringClass.getSimpleName() + '.' + methodName + '(' + parameters + ')',
            conversionFailedMethod);
}

From source file:com.amazonaws.services.dynamodbv2.datamodeling.DynamoDbPropertyMarshaller.java

public static <T extends Item> void setValue(final T item, final PropertyDescriptor propertyDescriptor,
        final AttributeValue attributeValue) {
    if (attributeValue != null) {
        final DynamoDBReflectorUtil reflector = new DynamoDBReflectorUtil();

        final Method writeMethod = propertyDescriptor.getWriteMethod();
        Object argument = null;//from   www  . j  a  va  2s.co m
        if (writeMethod != null) {
            try {
                final ArgumentUnmarshaller unmarshaller = reflector.getArgumentUnmarshaller(item,
                        propertyDescriptor.getReadMethod(), writeMethod, null);
                argument = unmarshaller.unmarshall(attributeValue);
            } catch (final DynamoDBMappingException | ParseException mappingException) {
                try {
                    final JsonParser jsonParser = jsonFactory
                            .createParser(new StringReader(attributeValue.getS()));
                    argument = jsonParser.readValueAs(writeMethod.getParameterTypes()[0]);
                } catch (final Exception e) {
                    throw new IllegalStateException("Could not parse attribute value: " + attributeValue, e);
                }
            }
            try {
                writeMethod.invoke(item, argument);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}