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

/**
 * Determine whether the given method is a "toString" method.
 * @see java.lang.Object#toString()//from  w  w  w .  j a  v  a  2 s.  c om
 */
public static boolean isToStringMethod(Method method) {
    return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
}

From source file:io.stallion.reflection.PropertyUtils.java

public static List<String> getPropertyNames(Class clazz) throws PropertyException {
    Method[] methods = clazz.getMethods();
    List<String> names = list();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        String name = method.getName();
        if (method.getModifiers() == Modifier.PUBLIC && method.getParameterTypes().length == 0
                && (name.startsWith("get") || name.startsWith("is"))
                && containsSetterForGetter(clazz, method)) {
            String propertyName;/*from w  w  w .  j a v  a2s  .c om*/
            if (name.startsWith("get"))
                propertyName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
            else
                propertyName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
            names.add(propertyName);
        }
    }
    return names;
}

From source file:com.xiongyingqi.util.ReflectionUtils.java

/**
 * Determine whether the given method is originally declared by {@link Object}.
 *///from   w ww.j av a 2  s  . c o m
public static boolean isObjectMethod(Method method) {
    try {
        Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
        return true;
    } catch (SecurityException ex) {
        return false;
    } catch (NoSuchMethodException ex) {
        return false;
    }
}

From source file:com.facebook.GraphObjectWrapper.java

private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) {
    if (hasClassBeenVerified(graphObjectClass)) {
        return;/*w w w .ja  va 2  s . c  o  m*/
    }

    if (!graphObjectClass.isInterface()) {
        throw new FacebookGraphObjectException(
                "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName());
    }

    Method[] methods = graphObjectClass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        int parameterCount = method.getParameterTypes().length;
        Class<?> returnType = method.getReturnType();
        boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class);

        if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) {
            // Don't worry about any methods from GraphObject or one of its base classes.
            continue;
        } else if (parameterCount == 1 && returnType == Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("set") && methodName.length() > 3) {
                // Looks like a valid setter
                continue;
            }
        } else if (parameterCount == 0 && returnType != Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("get") && methodName.length() > 3) {
                // Looks like a valid getter
                continue;
            }
        }

        throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString());
    }

    recordClassHasBeenVerified(graphObjectClass);
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Call a method on an object.//from  w ww.j  a  v  a  2  s . c om
 * 
 * @param obj
 *            the object
 * @param method
 *            the method name
 * @param args
 *            the arguments
 * @return the return value
 */
public static Object callMethod(Object obj, String method, Object[] args) {

    Class clazz = obj.getClass();

    for (Method m : clazz.getMethods()) {
        if (!m.getName().equals(method)) {
            continue;
        }
        Class[] argTypes = m.getParameterTypes();
        if (argTypes.length == args.length) {
            Object[] actualArgs = new Object[args.length];
            for (int i = args.length - 1; i >= 0; i--) {
                actualArgs[i] = ReflectUtils.coerceType(args[i], argTypes[i]);
            }
            try {
                return m.invoke(obj, actualArgs);
            } catch (Exception e) {
                throw new PaxmlRuntimeException(e);
            }
        }
    }
    throw new PaxmlRuntimeException("No method named '" + method + "' has " + args.length
            + " parameters from class: " + clazz.getName());
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Call a static method. If not found, exception will be thrown.
 * /*from  w  ww.  j  ava 2  s.c o m*/
 * @param className
 *            the class name
 * @param method
 *            the method name
 * @param args
 *            the args name
 * @return the method return value.
 * 
 */
public static Object callStaticMethod(String className, String method, Object[] args) {
    if (args == null) {
        args = new Object[0];
    }
    Class clazz = ReflectUtils.loadClassStrict(className, null);
    for (Method m : clazz.getMethods()) {
        if (!m.getName().equals(method)) {
            continue;
        }
        Class[] argTypes = m.getParameterTypes();
        if (argTypes.length == args.length) {
            Object[] actualArgs = new Object[args.length];
            for (int i = args.length - 1; i >= 0; i--) {
                actualArgs[i] = ReflectUtils.coerceType(args[i], argTypes[i]);
            }
            try {
                return m.invoke(null, actualArgs);
            } catch (Exception e) {
                throw new PaxmlRuntimeException(e);
            }
        }
    }
    throw new PaxmlRuntimeException(
            "No method named '" + method + "' has " + args.length + " parameters from class: " + className);
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Determine whether the given method is an "equals" method.
 * //from   ww w  . ja  v a 2s . co  m
 * @see java.lang.Object#equals
 */
public static boolean isEqualsMethod(final Method method) {
    if (method == null || !method.getName().equals("equals")) {
        return false;
    }
    final Class<?>[] parameterTypes = method.getParameterTypes();
    return parameterTypes.length == 1 && parameterTypes[0] == Object.class;
}

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

public static void populateObject(String operatorName, int operatorNum, String dataFlowName,
        Map<String, Object> objectProperties, Object top, EngineImportService engineImportService,
        EPDataFlowOperatorParameterProvider optionalParameterProvider,
        Map<String, Object> optionalParameterURIs) throws ExprValidationException {
    Class applicableClass = top.getClass();
    Set<WriteablePropertyDescriptor> writables = PropertyHelper.getWritableProperties(applicableClass);
    Set<Field> annotatedFields = JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class);
    Set<Method> annotatedMethods = JavaClassHelper.findAnnotatedMethods(top.getClass(),
            DataFlowOpParameter.class);

    // find catch-all methods
    Set<Method> catchAllMethods = new LinkedHashSet<Method>();
    if (annotatedMethods != null) {
        for (Method method : annotatedMethods) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0);
            if (anno.all()) {
                if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class
                        && method.getParameterTypes()[1] == Object.class) {
                    catchAllMethods.add(method);
                    continue;
                }/*from  w  w w. j  a v  a2  s. c  o m*/
                throw new ExprValidationException("Invalid annotation for catch-call");
            }
        }
    }

    // map provided values
    for (Map.Entry<String, Object> property : objectProperties.entrySet()) {
        boolean found = false;
        String propertyName = property.getKey();

        // invoke catch-all setters
        for (Method method : catchAllMethods) {
            try {
                method.invoke(top, new Object[] { propertyName, property.getValue() });
            } catch (IllegalAccessException e) {
                throw new ExprValidationException("Illegal access invoking method for property '" + propertyName
                        + "' for class " + applicableClass.getName() + " method " + method.getName(), e);
            } catch (InvocationTargetException e) {
                throw new ExprValidationException("Exception invoking method for property '" + propertyName
                        + "' for class " + applicableClass.getName() + " method " + method.getName() + ": "
                        + e.getTargetException().getMessage(), e);
            }
            found = true;
        }

        if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) {
            continue;
        }

        // use the writeable property descriptor (appropriate setter method) from writing the property
        WriteablePropertyDescriptor descriptor = findDescriptor(applicableClass, propertyName, writables);
        if (descriptor != null) {
            Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(),
                    descriptor.getType(), engineImportService, false);

            try {
                descriptor.getWriteMethod().invoke(top, new Object[] { coerceProperty });
            } catch (IllegalArgumentException e) {
                throw new ExprValidationException("Illegal argument invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName() + " provided value " + coerceProperty, e);
            } catch (IllegalAccessException e) {
                throw new ExprValidationException("Illegal access invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName(), e);
            } catch (InvocationTargetException e) {
                throw new ExprValidationException("Exception invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName() + ": " + e.getTargetException().getMessage(),
                        e);
            }
            continue;
        }

        // find the field annotated with {@link @GraphOpProperty}
        for (Field annotatedField : annotatedFields) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations()).get(0);
            if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) {
                Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(),
                        annotatedField.getType(), engineImportService, true);
                try {
                    annotatedField.setAccessible(true);
                    annotatedField.set(top, coerceProperty);
                } catch (Exception e) {
                    throw new ExprValidationException(
                            "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
                }
                found = true;
                break;
            }
        }
        if (found) {
            continue;
        }

        throw new ExprValidationException("Failed to find writable property '" + propertyName + "' for class "
                + applicableClass.getName());
    }

    // second pass: if a parameter URI - value pairs were provided, check that
    if (optionalParameterURIs != null) {
        for (Field annotatedField : annotatedFields) {
            try {
                annotatedField.setAccessible(true);
                String uri = operatorName + "/" + annotatedField.getName();
                if (optionalParameterURIs.containsKey(uri)) {
                    Object value = optionalParameterURIs.get(uri);
                    annotatedField.set(top, value);
                    if (log.isDebugEnabled()) {
                        log.debug("Found parameter '" + uri + "' for data flow " + dataFlowName + " setting "
                                + value);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName);
                    }
                }
            } catch (Exception e) {
                throw new ExprValidationException(
                        "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
            }
        }

        for (Method method : annotatedMethods) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0);
            if (anno.all()) {
                if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class
                        && method.getParameterTypes()[1] == Object.class) {
                    for (Map.Entry<String, Object> entry : optionalParameterURIs.entrySet()) {
                        String[] elements = URIUtil.parsePathElements(URI.create(entry.getKey()));
                        if (elements.length < 2) {
                            throw new ExprValidationException("Failed to parse URI '" + entry.getKey()
                                    + "', expected " + "'operator_name/property_name' format");
                        }
                        if (elements[0].equals(operatorName)) {
                            try {
                                method.invoke(top, new Object[] { elements[1], entry.getValue() });
                            } catch (IllegalAccessException e) {
                                throw new ExprValidationException(
                                        "Illegal access invoking method for property '" + entry.getKey()
                                                + "' for class " + applicableClass.getName() + " method "
                                                + method.getName(),
                                        e);
                            } catch (InvocationTargetException e) {
                                throw new ExprValidationException(
                                        "Exception invoking method for property '" + entry.getKey()
                                                + "' for class " + applicableClass.getName() + " method "
                                                + method.getName() + ": " + e.getTargetException().getMessage(),
                                        e);
                            }
                        }
                    }
                }
            }
        }
    }

    // third pass: if a parameter provider is provided, use that
    if (optionalParameterProvider != null) {

        for (Field annotatedField : annotatedFields) {
            try {
                annotatedField.setAccessible(true);
                Object provided = annotatedField.get(top);
                Object value = optionalParameterProvider.provide(new EPDataFlowOperatorParameterProviderContext(
                        operatorName, annotatedField.getName(), top, operatorNum, provided, dataFlowName));
                if (value != null) {
                    annotatedField.set(top, value);
                }
            } catch (Exception e) {
                throw new ExprValidationException(
                        "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
            }
        }
    }
}

From source file:com.liferay.cli.support.util.ReflectionUtils.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</code>.//from w ww .j  ava  2  s.  c o m
 * <p>
 * Returns <code>null</code> if no {@link Method} can be found.
 * 
 * @param clazz the class to introspect
 * @param name the name of the method
 * @param parameterTypes the parameter types of the method (may be
 *            <code>null</code> to indicate any signature)
 * @return the Method object, or <code>null</code> if none found
 */
public static Method findMethod(final Class<?> clazz, final String name, final Class<?>[] parameterTypes) {
    Validate.notNull(clazz, "Class must not be null");
    Validate.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        final Method[] methods = searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods();
        for (final Method method : methods) {
            if (name.equals(method.getName())
                    && (parameterTypes == null || Arrays.equals(parameterTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

/**
 * For given class, returns a ReflectionHelper instance with property accessors for the class.
 * //  w  w w .j  a  va2 s . co m
 * @param clazz the class
 * @return the ReflectionHelper
 */
public static ReflectionHelper createReflectionHelper(Class<?> clazz) {
    final List<PropertyAccessor> accessors = new ArrayList<PropertyAccessor>();

    Class<?> currentClass = clazz;
    while (currentClass != null) {
        final Method[] methods = currentClass.getDeclaredMethods();
        for (final Method getter : methods) {
            if (getter.getName().startsWith("get") && getter.getParameterTypes().length == 0) {
                for (final Method setter : methods) {
                    if (setter.getName().equals('s' + getter.getName().substring(1))
                            && setter.getParameterTypes().length == 1
                            && Void.TYPE.equals(setter.getReturnType())
                            && getter.getReturnType().equals(setter.getParameterTypes()[0])) {
                        getter.setAccessible(true);
                        setter.setAccessible(true);
                        accessors.add(new PropertyAccessor(getter, setter));
                    }
                }
            }
        }

        currentClass = currentClass.getSuperclass();
    }

    return new ReflectionHelper(accessors.toArray(new PropertyAccessor[accessors.size()]));
}