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

What I want to do is easily transfer the real object of the method to another method. This means that I can create a generic Joiner function that integrates into a given method of a list of objects without the danger of simply passing a string representing this method. Is this possible in Java so that I can have a syntax like:

joinOnMethod(String, Collections<T>, Method) eg joinOnMethod(", ", someList, T.getName()) 

Where T.getName () passes the getName () method to call each object in the list instead of passing in the return type of the method itself.

Hope this is clear enough for my needs,

Alexey Blue.

+4
source share
4 answers

There is no support for first class functions in Java. Two options:

  • Pass the name of the method and use reflection to get it
  • Create a type with one element, for example:

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

    Then you can use an anonymous inner class, for example:

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

    Of course, you can extract this 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); 
+6
source

I suggest exploring the command pattern in Java. It supports callback functions.

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

+1
source

I bet you just switched to Java from Javascript or another language that treats functions as objects. As far as I know, this is not possible since Java does not treat functions as objects. You will need to write it in a for loop or some other construct.

+1
source

No, there is no such syntax. Moreover, due to type erasure, the actual type T not available at run time, so it would not be possible inside the general, even if the syntax were available.

The trick is to pass the Class<T> along with other parameters and use reflection to get the method:

 joinOnMethod(String separator, Collections<T> items, String methodName, Class<T> theClass) 

Now you can request a class for the methodName method and use this method in the calculations. This will not help you get away from passing strings (i.e., the Compiler will not cause an error if the method does not exist), but you can make it work with generics, despite the type being erased.

+1
source

Source: https://habr.com/ru/post/1413163/


All Articles