squ*_*ert 5 java oop generics methods polymorphism
我想使用一个类(一种类型)中的静态方法,
以使调用通用.
有没有办法实现这个功能?一些伪代码有助于举例说明我正在尝试做的事情:
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)