It's kinda hard to explain the problem so I will explain with the code below.
I would like to create the method applyAll.
applyAll take a setter method from the User class and call a function (passed as parameter) to set value of that method.
Problems are:
- what is the type of User::setLogin ?
- how can I call this generic method ?
public class UserBuilder {
private List<User> users;
/* ... */
public <T> UserBuilder applyAll(??? method, Function<Integer, T> func) {
for (int index = 0; index < users.size(); index++) {
// I don't know how to call 'method' parameter (which is a method of User class)
users.get(i)[method](func.apply(index));
}
return this;
}
public UserBuilder withLogin(Function<Integer, String> func) {
return applyAll(User::setLogin, func);
}
/* ... */
}
public class User {
private String login;
void setLogin(String login) { this.login = login; }
}
Example of use case:
List<User> users = new UserBuilder(10).withLogin((index) -> "user_" + index).build();
int, but a method reference cannot be anint. Do you meanmethod.apply(users.get(i))or something?Method(which is a description of a method in reflection) with a "method reference" (which is a way to represent a method as a lambda).