Send static methods as a parameter and generally call another method in Java

I want to use static methods from one class (one type),

  • send them to another method in another class and
  • call them within a class method without explicitly using their names

to make a general call .

Is there any way to achieve this functionality? Some pseudo codes that help show what I'm trying to do:

public class A { public static void aMethod1() { //do something } public static void aMethod2() { //do something else } } public class B { public void bMethod(<Parameter that can take any of A methods polymorphically>) { <call ANY method sent in by the parameter with the same line of code> } } public class Main { public static void main(String[] args) { A obj_A = new A(); B obj_B = new B(); obj_B.bMethod(<Send any of A methods>); } } 

I may be on the completely wrong path, but I think it can be done. Thank you for your help.

+5
source share
2 answers

Using method references:

Declare:

 public class B { public void bMethod(Runnable runnable) { runnable.run(); } } 

Now pass method references to bMethod()

 new B().bMethod(A::aMethod1); new B().bMethod(A::aMethod2); 

Using reflection

Declare:

 public class B { public void bMethod(Method method) { try { method.invoke(null) } catch (Exception e) { throw new RuntimeException(e); } } } 

Now pass the bMethod() methods via reflection :

 new B().bMethod(A.class.getMethod("aMethod1")); new B().bMethod(A.class.getMethod("aMethod2")); 
+9
source

Well, you can achieve this using reflection.

 public void bMethod(String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { A.class.getMethod(name).invoke(null); } 

Where name is the name of your method (be it aMethod1 or aMethod2 ).

However, this is not a real OOP method, and you should use a different approach. For example, define an interface named Behavior

 interface Behavior { void run(); } 

Then you create two different implementations of this interface.

 class BehaviorA implements Behavior { @Override public void run() { // Behavior A } } class BehaviorB implements Behavior { @Override public void run() { // Behavior B } } 

Now your bMethod signature inside your class B might look like this:

 void bMethod(Behavior b); 

And voila! You can pass two different behaviors to your method now, without using ugly reflection-based hacks.

+2
source

Source: https://habr.com/ru/post/1240874/


All Articles