How can you pass in an actual method as a parameter to another method in Java?

generics, java, methods

Solution

There's no first-class function support in Java directly. Two options:

- Pass in the name of the method, and use reflection to get at it

Create a type with a single member, like this:

public interface Function<In, Out> {
    Out apply(In input);
}

Then you can use an anonymous inner class, like this:

joinOnMethod(", ", someList, new Function<T, String>() {
                 @Override public String apply(T input) {
                     return input.getName();
                 }
             });

Of course you can extract that function as a variable:

private static Function<T, String> NAME_EXTRACTOR = 
    new Function<T, String>() {
        @Override public String apply(T input) {
            return input.getName();
        }
    };

...

joinOnMethod(", ", someList, NAME_EXTRACTOR);

Problem

What I want to do is to easily pass in an actual method object to another method. This is so I can create a generic Joiner function that joins on a given method of a list of objects without the danger of just passing in a string that represents the method. Is this possible in Java so that I can have syntax like: ``` joinOnMethod(String, Collections<T>, Method) e.g. joinOnMethod(", ", someList, T.getName()) ``` Where T.getName() passes the getName() method into be called on each object in the list instead of passing in the return type of the method itself. Hope this is clear enough for my needs, Alexei Blue.

Original source