Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 233
Alexei Blue Avatar asked Jan 16 '23 15:01

Alexei Blue


2 Answers

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);
    
like image 189
Jon Skeet Avatar answered Jan 20 '23 15:01

Jon Skeet


I suggest researching the command pattern in Java. It supports callback functionality.

http://en.wikipedia.org/wiki/Command_pattern#Java

like image 37
jn1kk Avatar answered Jan 20 '23 16:01

jn1kk