public static Method findMethod ( Object obj , String methodName , Object ... params ) { Class < ? > [ ] classArray = new Class < ? > [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { classArray [ i ] = params [ i ] . getClass ( ) ; } try { //look on all the public, protected, default and private methods of the class hierarchy. Class < ? > klass = obj . getClass ( ) ; while ( klass != null ) { for ( Method method : klass . getDeclaredMethods ( ) ) { //check if the method name matches along with the number of parameters if ( method . getName ( ) . equals ( methodName ) && method . getParameterCount ( ) == classArray . length ) { Class < ? > [ ] paramClasses = method . getParameterTypes ( ) ; //Then check one by one all the provided parameters and see if they match the defined ones. boolean parametersMatch = true ; for ( int i = 0 ; i < params . length ; i ++ ) { if ( ! paramClasses [ i ] . isAssignableFrom ( classArray [ i ] ) ) { parametersMatch = false ; break ; } } if ( parametersMatch ) { //exact match, return the method return method ; } } } klass = klass . getSuperclass ( ) ; } //nothing found throw new NoSuchMethodException ( ) ; } catch ( NoSuchMethodException ex ) { throw new RuntimeException ( ex ) ; } }
Finds the public protected default or private method of the object with the provided name and parameters .