Java Reflection Method Return getMethod(Class type, String name, Class returnType, Class paramType, boolean caseSensitive)

Here you can find the source of getMethod(Class type, String name, Class returnType, Class paramType, boolean caseSensitive)

Description

Gets the public method within the type that matches the method name, return type, and single parameter type.

License

Apache License

Parameter

Parameter Description
type The class to search for the method
name The name of the method to search for
returnType The expected return type or null if its expected to be a void method
paramType The expected parameter type or null if no parameters are expected
caseSensitive True if its a case sensitive search, otherwise false

Exception

Parameter Description

Return

The method matching the search criteria

Declaration

public static Method getMethod(Class<?> type, String name,
        Class<?> returnType, Class<?> paramType, boolean caseSensitive)
        throws IllegalAccessException, NoSuchMethodException 

Method Source Code

//package com.java2s;
/*//  w  ww. j  a va 2 s . co m
 * #%L
 * ch-commons-util
 * %%
 * Copyright (C) 2012 Cloudhopper by Twitter
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    /**
     * Gets the public method within the type that matches the method name, return type,
     * and single parameter type. Optionally is a case sensitive search. Useful
     * for searching for "bean" methods on classes.
     * @param type The class to search for the method
     * @param name The name of the method to search for
     * @param returnType The expected return type or null if its expected to be a void method
     * @param paramType The expected parameter type or null if no parameters are expected
     * @param caseSensitive True if its a case sensitive search, otherwise false
     * @return The method matching the search criteria
     * @throws java.lang.IllegalAccessException If the method was found, but is not public.
     * @throws java.lang.NoSuchMethodException If the method was not found
     */
    public static Method getMethod(Class<?> type, String name,
            Class<?> returnType, Class<?> paramType, boolean caseSensitive)
            throws IllegalAccessException, NoSuchMethodException {

        // flag to help modify the exception to make it a little easier for debugging
        boolean methodNameFound = false;

        // start our search
        Class<?> classType = type;

        while (classType != null && !classType.equals(Object.class)) {

            for (Method m : classType.getDeclaredMethods()) {

                if ((!caseSensitive && m.getName().equalsIgnoreCase(name))
                        || (caseSensitive && m.getName().equals(name))) {

                    // we found the method name, but its possible the signature won't
                    // match below, we'll set this flag to help construct a better exception
                    // below
                    methodNameFound = true;

                    // should we validate the return type?
                    if (returnType != null) {
                        // if the return types don't match, then this must be invalid
                        // since the JVM doesn't allow the same return type
                        if (!m.getReturnType().equals(returnType)) {
                            throw new NoSuchMethodException("Method '"
                                    + name + "' was found in "
                                    + type.getSimpleName() + ".class"
                                    + ", but the returnType "
                                    + m.getReturnType().getSimpleName()
                                    + ".class did not match expected "
                                    + returnType.getSimpleName() + ".class");
                        }
                        // make sure the return type is VOID
                    } else {
                        if (!m.getReturnType().equals(void.class)) {
                            throw new NoSuchMethodException("Method '"
                                    + name + "' was found in "
                                    + type.getSimpleName() + ".class"
                                    + ", but the returnType "
                                    + m.getReturnType().getSimpleName()
                                    + ".class was expected to be void");
                        }
                    }

                    // return type was okay, check the parameters
                    Class<?>[] paramTypes = m.getParameterTypes();

                    // should we check the parameter type?
                    if (paramType != null) {
                        // must have exactly 1 parameter
                        if (paramTypes.length != 1) {
                            // this might not be the method we want, keep searching
                            continue;
                        } else {
                            // if the parameters don't match, keep searching
                            if (!paramTypes[0].equals(paramType)) {
                                continue;
                            }
                        }
                        // if paramType was null, then make sure no parameters are expected
                    } else {
                        if (paramTypes.length != 0) {
                            continue;
                        }
                    }

                    // if we got here, then everything matches so far
                    // now its time to check if the method is accessible
                    if (!Modifier.isPublic(m.getModifiers())) {
                        throw new IllegalAccessException("Method '" + name
                                + "' was found in " + type.getSimpleName()
                                + ".class "
                                + ", but its not accessible since its "
                                + Modifier.toString(m.getModifiers()));
                    }

                    // everything was okay
                    return m;
                }
            }

            // move onto the superclass
            classType = classType.getSuperclass();
        }

        String signature = "public "
                + (returnType == null ? "void" : returnType.getName())
                + " " + name + "("
                + (paramType == null ? "" : paramType.getName()) + ")";

        if (methodNameFound) {
            throw new NoSuchMethodException("Method '" + signature
                    + "' was found in " + type.getSimpleName()
                    + ".class, but signature match failed");
        } else {
            throw new NoSuchMethodException("Method '" + signature
                    + "' was not found in " + type.getSimpleName()
                    + ".class");
        }
    }
}

Related

  1. getMethod(Class clazz, String methodName, Class returnType, Class... inputParams)
  2. getMethod(Class clazz, String name, String returnType, String[] args)
  3. getMethod(Class parentClass, Class returnType, String methodName, Class... types)
  4. getMethodByReturnType(final Class source, final Class type)
  5. getMethodByTypes(Class clazz, String name, Class returnType, Class... parameterTypes)
  6. getMethodDesc(Class returnType, Class... params)
  7. getMethode(Class clasS, Class Returntype, int modifier, Class... classes)