Re: getMethod() works and works not
 
On 11/27/2010 11:12 AM, Mike Schilling wrote:
5. If exactly one remains, call it. Otherwise throw an exception.
Done.
package test;
import javax.swing.*;
import java.lang.reflect.*;
public class F
{
    public static void main( String[] args )
            throws Exception
    {
       JFrame frame = new JFrame( "Title" );
       JPanel panel = (JPanel) frame.getContentPane();
       JTextArea area = new JTextArea( 10, 40 );
       frame.setSize( 300, 200 );
       frame.setLocation( 200, 200 );
       // This works ('add' JTextArea to JPanel):
       panel.add( area );
       // This, however, does not work (same 'add' JTextArea to JPanel):
       // ??? method = panel.getClass().getMethod("add",area.getClass());
       exeMethod( panel, "add", area );
       frame.setVisible( true );
    }
    public static Object exeMethod( Object o, String method, Object... 
params )
            throws NoSuchMethodException, IllegalAccessException,
                   IllegalArgumentException, InvocationTargetException
    {
       Method[] methodList;
       methodList = o.getClass().getMethods();
       Method invokeMethod = null;
       looking:    // looking for methods
       for( Method m : methodList ) {
          if( m.getName().equals( method ) ) {
             Class<?>[] paramTypes = m.getParameterTypes();
             if( paramTypes.length == params.length ) {
                for( int i = 0; i < paramTypes.length; i++ ) {
                   Class<?> class1 = paramTypes[i];
                   if( !(class1.isInstance( params[i] )) ) {
                      continue looking;
                   }
                }
                // all parameters check out:
                System.err.println( "Canidate: " + m );
                if( invokeMethod == null ) {
                   invokeMethod = m;
                } else {
                   // more than one canidate, bail
                   throw new IllegalArgumentException( method+
                           " has multiple canidates, cannot resolve.");
                }
             }
          }
       }
       return invokeMethod.invoke( o, params );
    }
}