Function pointers as parameters in Java 8

To reduce code duplication for every attribute update in the JPA, I would like to pass a pointer to doTransactionand call a function. How can I do this in 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();
}
+4
source share
2 answers

You can take Runnableas an argument doTransactionand pass it a lambda expression that updates the person. Here we use Runnableas a functional interface that defines a method that takes no parameters and does not return values.

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

public void doTransaction(Runnable action) {
    em.getTransaction().begin();
    action.run();
    em.getTransaction().commit();
}

, Runnable - , , , . , Action,

@FunctionalInterface
interface Action {
    void perform();
}

action.perform() doTransaction.

+5

void, a Runnable .

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

public void doTransaction(Ruunable runnable) {
    em.getTransaction().begin();
    runnable.run();
    em.getTransaction().commit();
}
+2

Source: https://habr.com/ru/post/1625047/


All Articles