我想知道是否可以有一个方法,其中另一个方法作为参数传递,因此第一个方法可以调用参数中传递的方法?
例如:
public void goToVisitManagementForm() throws ParseException {
if (isAuthenticated() && userTypeIs("Patient")) {
// I could have this whole block just moved to another method?
Panel newPanel = new Panel("Choose the details for your visit");
Component visitManagementForm = new VisitManagementForm(userData,
this);
newPanel.addComponent(visitManagementForm);
mainWindow.setMainPanel(newPanel);
} else {
authenticate();
}
}
如果代码块将被移动到另一个方法,并且它将作为参数传递给该方法。我怎样才能实现这一目标?这是一个好的做法吗?因为在这种情况下,我总是需要粘贴 ifs... 那么其他方面呢?
最佳答案
这称为 higher-order function并且您不能在 Java 7 或更低版本中执行此操作。您可以通过使用匿名类来模拟将函数传递给其他函数,该匿名类实例化函数所需的某些接口(interface),然后在该对象上调用该函数。
例如,传递无参数函数:
interface Function {
void apply();
}
void takesAFunction(Function function) {
function.apply();
}
然后下面的代码片段将执行您想要的操作:
Function myFunction = new Function() {
@Override
public void apply() {
// your code here.
}
};
takesAFunction(myFunction);
顺便说一句,反射对于此类问题来说是极端的杀伤力。
关于java - 是否可以创建一个方法来将方法作为参数传递并在其中调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14290492/