public static < R > R callInstanceMethod ( Class < ? > cl , final Object instance , final String methodName , ClassParameter < ? > ... classParameters ) { try { final Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; final Object [ ] values = ClassParameter . getValues ( classParameters ) ; Method method = cl . getDeclaredMethod ( methodName , classes ) ; method . setAccessible ( true ) ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { throw new IllegalArgumentException ( method + " is static" ) ; } return ( R ) method . invoke ( instance , values ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Reflectively call an instance method on an object on a specific class .