java - Accepting a method as input parameter for another method -


i seen apis accepting method parameter. no idea how work. may using reflection inside no idea how.

please tell me how should write method can accept method input? example;

somemethod(on(someclass.class).somemethod()); 

alternative:

somemethod("fieldname" , someclass.class); 

but not type safe. , creating enum burden.

in java write interface this:

public interface function{     public void apply();  } 

then can use function this:

static void main( string args[] ){     callsomemethod( new function(){         public void apply(){             system.out.println( "hurray" );          }     } ); }  static void callsomemethod( function f ){     f.apply();  } 

in java 8 simplified addition of lambdas. time being how it's done in java.

built-in classes

java has few built in classes generic. instance take @ callable: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/callable.html

reflection

you can use reflection. above example this:

class thing{     public void whatever(){         system.out.println( "hi!" );      } }  public static void main( string args[] ){     thing thing = new thing();      callsomemethod( thing, "whatever" );  }  public static void callsomemethod( object obj, string methodname ){     obj.getclass().getmethod( methodname ).invoke( obj );  } 

however, reflection pretty slow compared above method , lose static type safety. in suggest not doing way if not absolutely necessary.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -