JasperJ JasperJ - 1 month ago 10
Java Question

Passing function references as parameters

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?

Answer

I think you're looking for BiConsumer:

private static void applyDataToPerson(String data, String regex, Person person, BiConsumer<Person, String> action) {
    Matcher match = Pattern.compile(regex).matcher(data);
    if (match.matches()) action.accept(person, match.group(1));
}

Alternatively, you can shorten the method signature and use a single-argument Consumer that captures your person reference:

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. 
    applyData(data, "name: (\\w+)", person::setName);
    applyData(data, "address: (\\w+)", person::setAddress);
}

private static void applyData(String data, String regex, Consumer<String> action) {
    Matcher match = Pattern.compile(regex).matcher(data);
    if (match.matches()) action.accept(match.group(1));
}
Comments