Example usage for java.lang Class getMethod

List of usage examples for java.lang Class getMethod

Introduction

In this page you can find the example usage for java.lang Class getMethod.

Prototype

@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Usage

From source file:ar.com.zauber.commons.spring.web.CommandURLParameterGenerator.java

/**
 * @see #getURLParameter(Class, Set)/*from w  ww  .j a  va  2  s  .co  m*/
 */
public static String getURLParameter(final Class<?> cmdClass, final Map<Class<?>, Object> values) {
    final StringBuilder sb = new StringBuilder("?");
    final Pattern getter = Pattern.compile("^get(.*)$");
    boolean first = true;

    // look for getters
    for (final Method method : cmdClass.getMethods()) {
        final Matcher matcher = getter.matcher(method.getName());
        if (matcher.lookingAt() && matcher.groupCount() == 1 && method.getParameterTypes().length == 0
                && values.containsKey(method.getReturnType())) {
            try {
                cmdClass.getMethod("set" + matcher.group(1), new Class[] { method.getReturnType() });
                if (!first) {
                    sb.append("&");
                } else {
                    first = false;
                }

                sb.append(URLEncoder.encode(matcher.group(1).toLowerCase(), CHARSET));
                sb.append("=");
                sb.append(URLEncoder.encode(values.get(method.getReturnType()).toString(), CHARSET));
            } catch (Exception e) {
                // skip
            }
        }
    }

    return sb.toString();
}

From source file:TestSample.java

public static void run(Class which, String[] args) {
    TestSuite suite = null;/*from  ww w . j a va 2 s  .  c  o m*/
    if (args.length != 0) {
        try {
            java.lang.reflect.Constructor ctor;
            ctor = which.getConstructor(new Class[] { String.class });
            suite = new TestSuite();
            for (int i = 0; i < args.length; i++) {
                suite.addTest((TestCase) ctor.newInstance(new Object[] { args[i] }));
            }
        } catch (Exception e) {
            System.err.println("Unable to instantiate " + which.getName() + ": " + e.getMessage());
            System.exit(1);
        }

    } else {
        try {
            Method suite_method = which.getMethod("suite", new Class[0]);
            suite = (TestSuite) suite_method.invoke(null, null);
        } catch (Exception e) {
            suite = new TestSuite(which);
        }
    }
    junit.textui.TestRunner.run(suite);
}

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 ww .j a  v  a  2 s .c  om*/
     * 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:SocketFetcher.java

/**
 * Return a socket factory of the specified class.
 *///from www . ja  va  2 s .  co m
private static SocketFactory getSocketFactory(String sfClass) throws ClassNotFoundException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (sfClass == null || sfClass.length() == 0)
        return null;

    // dynamically load the class 

    ClassLoader cl = getContextClassLoader();
    Class clsSockFact = null;
    if (cl != null) {
        try {
            clsSockFact = cl.loadClass(sfClass);
        } catch (ClassNotFoundException cex) {
        }
    }
    if (clsSockFact == null)
        clsSockFact = Class.forName(sfClass);
    // get & invoke the getDefault() method
    Method mthGetDefault = clsSockFact.getMethod("getDefault", new Class[] {});
    SocketFactory sf = (SocketFactory) mthGetDefault.invoke(new Object(), new Object[] {});
    return sf;
}

From source file:Main.java

public static void setProperties(Object object, Map<String, ? extends Object> properties,
        boolean includeSuperClasses) {
    if (object == null || properties == null) {
        return;// w ww .j  a  v  a  2 s  . c  o m
    }

    Class<?> objectClass = object.getClass();

    for (Map.Entry<String, ? extends Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (key != null && key.length() > 0) {
            String setterName = "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);
            Method setter = null;

            // Try to use the exact setter
            if (value != null) {
                try {
                    if (includeSuperClasses) {
                        setter = objectClass.getMethod(setterName, value.getClass());
                    } else {
                        setter = objectClass.getDeclaredMethod(setterName, value.getClass());
                    }
                } catch (Exception ex) {
                }
            }

            // Find a more generic setter
            if (setter == null) {
                Method[] methods = includeSuperClasses ? objectClass.getMethods()
                        : objectClass.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.getName().equals(setterName)) {
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        if (parameterTypes.length == 1 && isAssignableFrom(parameterTypes[0], value)) {
                            setter = method;
                            break;
                        }
                    }
                }
            }

            // Invoke
            if (setter != null) {
                try {
                    setter.invoke(object, value);
                } catch (Exception e) {
                }
            }
        }
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

private static Method _findMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes)
        throws NoSuchMethodException {
    Method method = null;/*  w ww .jav a  2 s .  c o  m*/
    try {
        method = clazz.getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
        try {
            method = clazz.getDeclaredMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ignore) {
        }
    }
    if (method == null) {
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            method = _findMethod(superClazz, methodName, parameterTypes);
        }
        if (method == null) {
            throw new NoSuchMethodException("Method: " + methodName);
        } else {
            return method;
        }
    } else {
        return method;
    }
}

From source file:com.haulmont.cuba.core.config.type.TypeFactory.java

/**
 * Get a TypeFactory instance appropriate for the return type of the
 * specified configuration interface method.
 *
 * @param configInterface The configuration interface.
 * @param method          The method.//from   w ww.ja  v  a 2  s  . c  o  m
 * @return An appropriate TypeFactory.
 * @throws IllegalArgumentException If the type is not supported.
 */
public static TypeFactory getInstance(Class<?> configInterface, Method method) {
    Class<?> returnType = method.getReturnType();
    if (returnType.isPrimitive()) {
        returnType = ClassUtils.primitiveToWrapper(returnType);
    }
    Factory factory = ConfigUtil.getAnnotation(configInterface, method, Factory.class, true);
    if (factory != null) {
        try {
            if ("".equals(factory.method())) {
                return factory.factory().newInstance();
            } else {
                String methodName = factory.method();
                Method factoryMethod = returnType.getMethod(methodName, String.class);
                if (!isAcceptableMethod(returnType, factoryMethod)) {
                    throw new IllegalArgumentException("Invalid factory method: " + factoryMethod);
                }
                return new StaticTypeFactory(factoryMethod);
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Unable to instantiate an type factory", e);
        }
    } else {
        if (Entity.class.isAssignableFrom(returnType)) {
            return AppBeans.get(ENTITY_FACTORY_BEAN_NAME, TypeFactory.class);
        } else {
            if (EnumClass.class.isAssignableFrom(returnType)) {
                EnumStore mode = ConfigUtil.getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    @SuppressWarnings("unchecked")
                    Class<EnumClass> enumeration = (Class<EnumClass>) returnType;
                    Class<?> idType = ConfigUtil.getEnumIdType(enumeration);
                    TypeFactory idFactory = getInferred(idType);
                    try {
                        Method fromIdMethod = returnType.getMethod("fromId", idType);
                        if (!isAcceptableMethod(returnType, fromIdMethod) || idFactory == null) {
                            throw new IllegalArgumentException(
                                    "Cannot use method as factory method: " + method);
                        }
                        return new EnumClassFactory(idFactory, fromIdMethod);
                    } catch (NoSuchMethodException e) {
                        throw new IllegalArgumentException(
                                "fromId method is not found for " + enumeration.getName());
                    }
                }
            }
            TypeFactory factoryT = getInferred(returnType);
            if (factoryT == null) {
                throw new IllegalArgumentException("Unsupported return type for " + method);
            }
            return factoryT;
        }
    }
}

From source file:com.yahoo.elide.core.EntityDictionary.java

/**
 * Find an arbitrary method./*from   ww w.j a  v  a2s. c  o m*/
 *
 * @param entityClass the entity class
 * @param name the name
 * @param paramClass the param class
 * @return method method
 * @throws NoSuchMethodException the no such method exception
 */
public static Method findMethod(Class<?> entityClass, String name, Class<?>... paramClass)
        throws NoSuchMethodException {
    Method m = entityClass.getMethod(name, paramClass);
    int modifiers = m.getModifiers();
    if (Modifier.isAbstract(modifiers)
            || (m.isAnnotationPresent(Transient.class) && !m.isAnnotationPresent(ComputedAttribute.class))) {
        throw new NoSuchMethodException(name);
    }
    return m;
}

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// w w  w  . j  a va2  s.c o  m
 * @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:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * @param cls the class to search the main in.
 * @param args command line args for the main class invoked.
 * @param useGUI <code>true</code> if the {@link GenericGUI} should be launched.
 * @return <code>true</code> if the class contains a <code>static main(String[])</code> that was invoked,
 *         <code>false</code> otherwise.
 * @see GenericGUI/*  w  w  w  .j a  v  a2  s  .  c o m*/
 */
private static boolean tryInvokeMain(Class<?> cls, String[] args, boolean useGUI) {
    try {
        if (useGUI) {
            @SuppressWarnings("unchecked")
            Class<SOMToolboxApp> sta = (Class<SOMToolboxApp>) cls;
            new GenericGUI(sta, args).setVisible(true);
            return true;
        }
    } catch (ClassCastException cce) {
        // Nop, continue...
    }

    try {
        Method main = cls.getMethod("main", String[].class);

        // special handling - if the parameter "--help" is present, also print the description
        if (ArrayUtils.contains(args, "--help")) {
            Object description = null;
            try { // try to get the LONG_DESCRIPTION field
                description = cls.getField("LONG_DESCRIPTION").get(null) + "\n";
            } catch (Exception e) {
                try { // fall back using the DESCRIPTION field
                    description = cls.getField("DESCRIPTION").get(null) + "\n";
                } catch (Exception e1) { // nothing found => write nothing...
                    description = "";
                }
            }
            System.out.println(description);
            try {
                Parameter[] options = (Parameter[]) cls.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                JSAPResult jsapResult = OptionFactory.parseResults(args, jsap, cls.getName());
                AbstractOptionFactory.printUsage(jsap, cls.getName(), jsapResult, null);
                return true;
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }
        }

        main.invoke(null, new Object[] { args });
        return true;
    } catch (InvocationTargetException e) {
        // If main throws an error, print it
        e.getCause().printStackTrace();
        return true;
    } catch (Exception e) {
        // Everything else is hidden...
        return false;
    }
}