Is it possible to pass a reference to a method as a parameter?
For example:
public static void main(String[] args) {
String data = "name: John, random text, address: leetStreet";
Person person;
//if regex matches, use method reference, to send the result.
applyDataToPerson(data, "name: (\\w+)", person, Person::setName);
applyDataToPerson(data, "address: (\\w+)", person, Person::setAddress);
}
private static void applyDataToPerson(String data, String regex, Person person,
Function<Person> f) {
Matcher match = Pattern.compile(regex).matcher(data);
if (match.matches()) person.f(match.group(1));
}
class Person {
private String name;
private String address;
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
If not, what would be an alternative to giving a reference to a method? Switch-case construct?
Comparator <? super T>does not make sense to me.Function<Person>supposed to represent? If we're talking aboutjava.util.function.Function, it has 2 generic types, not 1. So that code cannot compile to begin with... (let aloneperson.f(...)). Before asking for alternatives, make sure you have working code...