Pass method to method as an argument in Java -



Pass method to method as an argument in Java -

i want pass method method argument , want develop scheme follows.

how can develop in java?

pseudo code:

class { public void test(method method, method method2) { if(condition) { method.run(); } else { method2.run(); } } } class b { a = new a(); a.test(foo(),bar()); public void foo() { print "hello"; } public void bar() { } }

you don't pass method. pass object of class implementing interface. in case, existing runnable interface fit nicely, since has single run method no input arguments , no homecoming value.

class { public void test(runnable method, runnable method2) { if(condition) { method.run(); } else { method2.run(); } } } class b { public static void main (string[] args) { a = new a(); runnable r1 = new runnable() { public void run() { system.out.println("hello1"); } }; runnable r2 = new runnable() { public void run() { system.out.println("hello2"); } }; a.test(r1,r2); } }

if using java 8, can simplify syntax lambda expressions :

class b { public static void main (string[] args) { a = new a(); a.test(() -> system.out.println("hello1"),() -> system.out.println("hello2")); } }

or can utilize method references (again, in java 8), compiler can match functional interface expected test() method :

class b { public static void main (string[] args) { a = new a(); a.test(b::foo,b::bar); // though foo() , bar() must static in case, // or wouldn't match signature of run() // method of runnable interface expected test() } }

java

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -