There is a much faster and easier way to accomplish it.
This post here also includes some previous answers.
The first class declarations are just to make the example compilable.
The interesting parts start after the method getCount()
package snippet;
import java.io.IOException;
import java.util.List;
public class LamdaExample {
// dummy declarations
static class User {}
static class EmailService {
public void sendEmailOne(final List<User> pUsers, final Integer pCount) {}
public void sendEmailTwo(final List<User> pUsers, final Integer pCount) {}
}
static class UserService {
public List<User> getUsers() {
return null;
}
}
public LamdaExample() {}
private final UserService userService = new UserService();
private final EmailService emailService = new EmailService();
private Integer getCount() {
return null;
}
// interesting part comes here
public void methodOne() {
System.out.println("LamdaExample.methodOne()");
final List<User> users = userService.getUsers();
final Integer count = getCount();
emailService.sendEmailOne(users, count);
}
public void methodTwo() {
System.out.println("LamdaExample.methodTwo()");
final List<User> users = userService.getUsers();
final Integer count = getCount();
emailService.sendEmailTwo(users, count);
}
public void method(final Runnable sendEmail) {
final List<User> users = userService.getUsers();
final Integer count = getCount();
sendEmail.run();
}
public static void main(final String[] args) {
// simple runnable, see code above
final LamdaExample t = new LamdaExample();
t.method(() -> t.methodOne());
t.method(() -> t.methodTwo());
// extended special functional interface, see code below
t.methodSpecial((p, q) -> t.methodX(p, q));
t.methodSpecial((p, q) -> t.methodY(q, p));
}
// extended example starts here
@FunctionalInterface
interface MySpecialInterface {
double specialMethod(String param1, Class<?> param2) throws IOException;
}
public void methodSpecial(final MySpecialInterface sendEmail) {
final List<User> users = userService.getUsers();
final Integer count = getCount();
try {
sendEmail.specialMethod("lol", this.getClass());
} catch (final IOException e) {
e.printStackTrace();
}
}
public double methodX(final String pP, final Class<?> pQ) {
System.out.println("LamdaExample.methodX()");
final List<User> users = userService.getUsers();
final Integer count = getCount();
emailService.sendEmailOne(users, count);
return 123.456;
}
public double methodY(final Class<?> pQ, final String pP) {
System.out.println("LamdaExample.methodY()");
final List<User> users = userService.getUsers();
final Integer count = getCount();
emailService.sendEmailTwo(users, count);
return 98.765;
}
}
, Integer> sendEmail) { .... sendEmail.accept(users, count); .... }` and call it by passing `emailService::sendEmailOne`.
– luk2302 Jan 31 '22 at 16:18