如何在声明实例之前将类方法作为参数传递?

时间:2016-09-23 08:20:25

标签: java

我想做的就是这样。我的问题是如何在内部调用tm.test。

// TestMain is a class implemented handler

public void outer() {
    inner(TestMain::test);  // call inner
}

public void inner(handler h) {
    TestMain tm = new TestMain();
    //invoke tm.h(), i.e. invoke tm.test() in this example
}

public interface handler<M> {
    void entitySelector();
}
  • 我知道如果在方法外部声明tm,如何在内部调用tm.test,即将函数作为tm :: test
  • 传递
  • 但每次打电话给内心时我都要申报实例。

1 个答案:

答案 0 :(得分:1)

简单地说:你做不到。即便有可能,你也不应该这样做。

有“最少惊喜的原则”:你不是那些读你的代码的人告诉你“wtf?!”因为你的代码让他们感到惊讶。

换句话说:你应该退一步看看你的设计是否真的有道理。例如,您不能使用固定的tm实例;一个在你班上作为领域的人;而不是你的方法中的局部变量?

相关问题