将静态方法作为参数发送,并在Java中的另一个方法中进行通用调用

squ*_*ert 5 java oop generics methods polymorphism

我想使用一个类(一种类型)中的静态方法,

  1. 将它们发送到另一个类中的另一个方法,并且
  2. 在不明确使用其名称的情况下,在不同类的方法中调用它们

以使调用通用.

有没有办法实现这个功能?一些伪代码有助于举例说明我正在尝试做的事情:

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's 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's methods>);
     }
}
Run Code Online (Sandbox Code Playgroud)

我可能走错了路,但这就是我想象的可能.感谢您的帮助.

Luk*_*der 11

使用方法参考:

宣布:

public class B
{
     public void bMethod(Runnable runnable)
     {
          runnable.run();
     }
}
Run Code Online (Sandbox Code Playgroud)

现在,通过方法引用bMethod()

new B().bMethod(A::aMethod1);
new B().bMethod(A::aMethod2);
Run Code Online (Sandbox Code Playgroud)

用反射

宣布:

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

现在将方法传递给bMethod() via反射:

new B().bMethod(A.class.getMethod("aMethod1"));
new B().bMethod(A.class.getMethod("aMethod2"));
Run Code Online (Sandbox Code Playgroud)