user3957817
user3957817

Reputation:

Function Pointers as Parameters in Java 8

To reduce code duplication for every update of an attribute in JPA, I'd like to hand over a function pointer to doTransaction and invoke the function. How can I do that 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();
}

Upvotes: 4

Views: 1439

Answers (2)

Tunaki
Tunaki

Reputation: 137184

You could accept a Runnable as argument of doTransaction and pass it a lambda expression updating the person. Here, we are only using Runnable as a functional interface that defines a method taking no parameters and returning no value.

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

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

If you think the name Runnable is somehow too linked to threads, you could roll your own interface defining a functional method taking no parameters and returning no value. For example, if you want to name it Action, you could have

@FunctionalInterface
interface Action {
    void perform();
}

and then call action.perform() inside doTransaction.

Upvotes: 5

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

In this case you need a parameterless void function, a Runnable would be sufficient.

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

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

Upvotes: 2

Related Questions