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:Mopex.java

/**
 * Return a string that represents the signature of the specified method.
 * /* ww  w. j  a v a  2  s  .co m*/
 * @return String
 * @param m
 *            java.lang.Method
 */
//start extract signatureToString
public static String signatureToString(Method m) {
    return m.getName() + "(" + formalParametersToString(m.getParameterTypes()) + ")";
}

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

/**
 * Returns the given base class' method if the given method (declared in the
 * interface) was also declared at the base class. Returns the given method
 * if the given base class does not declare the method given. Takes generics
 * into account.// w ww .  j a  va 2s.c  o m
 * 
 * @param method
 * @param baseClass
 * @param daoInterface
 * @return
 */
public static Method getBaseClassMethodFor(Method method, Class<?> baseClass, Class<?> daoInterface) {

    for (Method daoClassMethod : baseClass.getMethods()) {

        // Wrong name
        if (!method.getName().equals(daoClassMethod.getName())) {
            continue;
        }

        // Wrong number of arguments
        if (!(method.getParameterTypes().length == daoClassMethod.getParameterTypes().length)) {
            continue;
        }

        // Check whether all parameters match
        if (!parametersMatch(method, daoClassMethod, daoInterface)) {
            continue;
        }

        return daoClassMethod;
    }

    return method;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static boolean[] findByRefParams(Method method) {

    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    Class<?>[] paramTypes = method.getParameterTypes();
    return findByRefParams(paramAnnotations, paramTypes);

}

From source file:Mopex.java

/**
 * Returns a string for a cooperative override of the method m. That is, The
 * string has the same return type and signature as m but the body has a
 * super call that is sandwiched between the strings code1 and code2.
 * //from  w w w  . j a va  2s.c om
 * @return String
 * @param m
 *            java.lang.Method
 * @param code1
 *            String
 * @param code2
 *            String
 */
//start extract createCooperativeWrapper
public static String createCooperativeWrapper(Method m, String code1, String code2) {
    Class[] pta = m.getParameterTypes();
    Class retType = m.getReturnType();
    String fpl = formalParametersToString(pta);
    String apl = actualParametersToString(pta);
    Class[] eTypes = m.getExceptionTypes();
    String result = retType.getName() + " " + m.getName() + "(" + fpl + ")\n";
    if (eTypes.length != 0)
        result += "    throws " + classArrayToString(eTypes) + "\n";
    result += "{\n" + code1 + "    ";
    if (retType != void.class)
        result += retType.getName() + " cooperativeReturnValue = ";
    result += "super." + m.getName() + "(" + apl + ");\n";
    result += code2;
    if (retType != void.class)
        result += "    return cooperativeReturnValue;\n";
    result += "}\n";
    return result;
}

From source file:RealFunctionValidation.java

public static SummaryStatistics assessAccuracy(final Method method, final DataInputStream in,
        final DataOutputStream out)
        throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    if (method.getReturnType() != Double.TYPE) {
        throw new IllegalArgumentException("method must return a double");
    }/*from  ww w .  j a  va 2 s  . c o  m*/

    final Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        if (!types[i].isPrimitive()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("argument #").append(i + 1).append(" of method ").append(method.getName())
                    .append("must be of primitive of type");
            throw new IllegalArgumentException(builder.toString());
        }
    }

    final SummaryStatistics stat = new SummaryStatistics();
    final Object[] parameters = new Object[types.length];
    while (true) {
        try {
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = readAndWritePrimitiveValue(in, out, types[i]);
            }
            final double expected = in.readDouble();
            if (FastMath.abs(expected) > 1E-16) {
                final Object value = method.invoke(null, parameters);
                final double actual = ((Double) value).doubleValue();
                final double err = FastMath.abs(actual - expected);
                final double ulps = err / FastMath.ulp(expected);
                out.writeDouble(expected);
                out.writeDouble(actual);
                out.writeDouble(ulps);
                stat.addValue(ulps);
            }
        } catch (EOFException e) {
            break;
        }
    }
    return stat;
}

From source file:ReflectUtil.java

/**
 * Fetches all methods of all access types from the supplied class and super
 * classes. Methods that have been overridden in the inheritance hierarchy are
 * only returned once, using the instance lowest down the hierarchy.
 *
 * @param clazz the class to inspect/*  w  w  w  .  j  av  a  2s.c  om*/
 * @return a collection of methods
 */
public static Collection<Method> getMethods(Class<?> clazz) {
    Collection<Method> found = new ArrayList<Method>();
    while (clazz != null) {
        for (Method m1 : clazz.getDeclaredMethods()) {
            boolean overridden = false;

            for (Method m2 : found) {
                if (m2.getName().equals(m1.getName())
                        && Arrays.deepEquals(m1.getParameterTypes(), m2.getParameterTypes())) {
                    overridden = true;
                    break;
                }
            }

            if (!overridden)
                found.add(m1);
        }

        clazz = clazz.getSuperclass();
    }

    return found;
}

From source file:org.jdbcluster.JDBClusterUtil.java

/**
 * Tries to determine the best fitting method for a set of parameter types.
 * Uses getMethod() first, if there is no direct match every parameter is
 * checked if there is a method with a superclass or superinterface match.
 * etc. For this best fitting method a scoring is used. It counts for every
 * parameter the "distance" from the class to the requested superclass or
 * superinterface. These "distances" are cummulated to one value. The method
 * with the lowest scoring value is returned.
 * //from   w w  w . ja  v a2  s .c  o m
 * @see #getMethod(Class, String, Class[])
 * @param clazz
 *            Class of Object
 * @param methodName
 *            name of the method to find
 * @param parameterTypes
 *            parameter types of method
 * @return Method to find
 */
static public Method getMethodBestParameterFit(Class clazz, String methodName, Class... parameterTypes) {

    /*
     * first try the normal way (exact match)
     */
    try {
        return JDBClusterUtil.getMethod(clazz, methodName, parameterTypes);
    } catch (ConfigurationException e) {
        if (!(e.getCause() instanceof NoSuchMethodException))
            throw e;
    }

    /*
     * get all methods and select only equal name and parameter length in
     * mList
     */
    Method[] mAll = clazz.getMethods();
    List<Method> mList = new ArrayList<Method>();

    for (Method m : mAll) {
        if (m.getParameterTypes().length == parameterTypes.length && m.getName().equals(methodName))
            mList.add(m);
    }

    if (mList.size() > 1)
        logger.warn("possible ambiguity. Found more than one method with name [" + methodName + "]. "
                + "trying best fit method");

    /*
     * check if parameter superclasses do fit for all above selected methods
     */
    HashMap<Method, Integer> methodScore = new HashMap<Method, Integer>();
    for (Method m : mList) {
        Class<?>[] mParameterTypes = m.getParameterTypes();

        for (int i = 0; i < parameterTypes.length; i++) {
            int count = countSuper(mParameterTypes[i], parameterTypes[i]);
            Integer oldInt = methodScore.get(m);
            if (oldInt == null)
                oldInt = 0;
            methodScore.put(m, oldInt + count);
            if (count < 0) {
                methodScore.put(m, -1);
                break; // if there is no match this method is not fitting
            }
        }
    }

    /*
     * evaluate scoring
     */
    Method mResult = null;
    int resultScore = Integer.MAX_VALUE;
    for (Method m : mList) {
        int score = methodScore.get(m);
        if (score != -1) {
            if (score < resultScore) {
                resultScore = score;
                mResult = m;
            }
        }
    }

    if (mResult == null)
        throw new ConfigurationException(
                "cant get MethodBestParameterFit for method [" + methodName + "] with the specified name");

    return mResult;
}

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * If the given class is public and has a Method that declares the
 * same name and arguments as the given method, then that method is
 * returned.  Otherwise the superclass and interfaces are searched
 * recursively.//from   w  w  w. j  ava  2s. co  m
 */
static Method getPublicMethod(Class pClass, Method pMethod) {
    // See if this is a public class declaring the method
    if (Modifier.isPublic(pClass.getModifiers())) {
        try {
            Method m;
            try {
                m = pClass.getDeclaredMethod(pMethod.getName(), pMethod.getParameterTypes());
            } catch (java.security.AccessControlException ex) {
                // kludge to accommodate J2EE RI's default settings
                // TODO: see if we can simply replace
                //       getDeclaredMethod() with getMethod() ...?
                m = pClass.getMethod(pMethod.getName(), pMethod.getParameterTypes());
            }
            if (Modifier.isPublic(m.getModifiers())) {
                return m;
            }
        } catch (NoSuchMethodException exc) {
        }
    }

    // Search the interfaces
    {
        Class[] interfaces = pClass.getInterfaces();
        if (interfaces != null) {
            for (int i = 0; i < interfaces.length; i++) {
                Method m = getPublicMethod(interfaces[i], pMethod);
                if (m != null) {
                    return m;
                }
            }
        }
    }

    // Search the superclass
    {
        Class superclass = pClass.getSuperclass();
        if (superclass != null) {
            Method m = getPublicMethod(superclass, pMethod);
            if (m != null) {
                return m;
            }
        }
    }

    return null;
}

From source file:org.caratarse.auth.model.util.BeanUtils.java

/**
 * Copy the not-null property values of the given source bean into the given target bean.
 * <p>//from   w  ww  .j  a v  a2s  . co  m
 * Note: The source and target classes do not have to match or even be derived from each other,
 * as long as the properties match. Any bean properties that the source bean exposes but the
 * target bean does not will silently be ignored.
 *
 * @param source the source bean
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyNotNullProperties(Object source, Object target, Class<?> editable,
        String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = org.springframework.beans.BeanUtils.getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = org.springframework.beans.BeanUtils
                    .getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (value == null) {
                            continue;
                        }
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:no.uis.service.ws.studinfosolr.impl.SolrUpdaterImpl.java

private static Object getValue(Object fsType, PropertyInfo pi) {
    try {/* w  ww.java2  s  . co  m*/
        Method mIsSet = pi.getIsSet();
        if (mIsSet != null) {
            if (!(boolean) mIsSet.invoke(fsType)) {
                return null;
            }
        }

        Method mGet = pi.getGet();
        if (mGet != null && mGet.getParameterTypes().length == 0) {
            return mGet.invoke(fsType);
        }
    } catch (Exception ex) {
        LOG.error("get " + pi.getPropName(), ex);
    }
    return null;
}