Re: Alternative to if...else for keyword based actions
c0balt279@gmail.com writes:
How can I [...] call a method based on a string name of the method?
To call a method by the string, for example, ?"method"? (and
here, for example, with the argument list ?( 5, 9 )?),
CallMethod.java
class Example
{
public static int method( int x, int y ){ return x + y; }
public static double method( double x, double y )
{ return x + y; }}
public class CallMethod
{
public static void main( String s[] ) { try
{
Class example = Class.forName( "Example" );
Class[] parameterTypes = new Class[]{ int.class, int.class };
java.lang.reflect.Method method = example.getMethod( "method", parameterTypes );
Object[] arguments = new Object[]{ new Integer( 5 ), new Integer( 9 )};
Object instance = null;
Integer result =( Integer )method.invoke( instance, arguments );
System.out.print( result.intValue() ); }
catch( Exception e ){} }}
System.out
14
BTW: Java 7 might get a string switch:
http://tech.puredanger.com/java7#switch