函数指针作为Java 8中的参数

4 java jpa java-8

为了减少JPA中每个属性更新的代码重复,我想将函数指针交给doTransaction并调用该函数.我怎么能在Java 8中做到这一点?

public void modifySalary(Person person, float salary) {
    doTransaction(person.setSalary(salary));
}

public void doTransaction(final Function<Void, Void> func) {
    em.getTransaction().begin();
    func.apply(null);
    em.getTransaction().commit();
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 5

你可以接受一个Runnableas参数doTransaction并传递一个lambda表达式来更新这个人.在这里,我们仅使用Runnable作为功​​能接口来定义不带参数且不返回任何值的方法.

public void modifySalary(Person person, float salary) {
    doTransaction(() -> person.setSalary(salary));
}

public void doTransaction(Runnable action) {
    em.getTransaction().begin();
    action.run();
    em.getTransaction().commit();
}
Run Code Online (Sandbox Code Playgroud)

如果您认为Runnable这个名称在某种程度上与线程有关,那么您可以滚动自己的接口来定义一个不带参数且不返回任何值的函数方法.例如,如果要为其命名Action,则可以

@FunctionalInterface
interface Action {
    void perform();
}
Run Code Online (Sandbox Code Playgroud)

然后打电话action.perform()到里面doTransaction.

  • @msch实际上,这就是我的观点.在这种情况下,我们只是使用它,因为它是一个现有的功能接口,不带参数,不返回任何值.任何线程都没有真正的链接.我的答案的第二部分只是提供一个替代名称. (2认同)
  • [Here](http://stackoverflow.com/q/27973294/2711488)Brian Goetz在评论中证实了这一点. (2认同)