How to create constructor in java parameterized with class?
Solution 1:
Use lambdas and pass the method reference: they match on the method signature. For void someStaticMethod()
you can use Runnable
.
class MyClass{
private final Runnable methodToRun;
public MyClass(Runnable someStaticMethod) {
methodToRun = someStaticMethod;
}
public void runClass(){
methodToRun.run();
}
}
new MyClass(SomeClass::someStaticMethod).runClass();
You cannot enforce that the method passed has the right name, but looks even neater IMHO.