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.
There's no first-class function support in Java directly. Two options:
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);
I suggest researching the command pattern in Java. It supports callback functionality.
http://en.wikipedia.org/wiki/Command_pattern#Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With