How to declare an array of method references?

I know how to declare an array of other things, like strings, as follows:

String[] strings = { "one", "two", "tree" };
// or
String[] strings = new String[] { "one", "two", "tree" };

But when it comes to method references, I can't figure out how to avoid to create a list and add each item individually.

Example. Call the method smartListMergeon several different matching lists from two sources:

List<Function<TodoUser, TodoList>> listGetters = new ArrayList<>(3);
listGetters.add(TodoUser::getPendingList);
listGetters.add(TodoUser::getCompletedList);
listGetters.add(TodoUser::getWishList);

TodoUser userA = ..., userB = ...;
for (Function<TodoAppUser, TodoList> listSupplier : listGetters) {
    TodoList sourceList = listSupplier.apply(userA);
    TodoList destinationList = listSupplier.apply(userB);

    smartListMerge(sourceList, destinationList);
}

What is the correct way to declare an array of method references?

+4
source share
3 answers

There are shorter ways to create a list:

List<Function<TodoUser, TodoList>> listGetters = Arrays.asList(TodoUser::getPendingList,
                                                               TodoUser::getCompletedList,
                                                               TodoUser::getWishList);

or (in Java 9):

List<Function<TodoUser, TodoList>> listGetters = List.of(TodoUser::getPendingList,
                                                         TodoUser::getCompletedList,
                                                         TodoUser::getWishList);
+3
source

In your question, you asked for an array of methods. You can define it as follows:

Method toString = String.class.getMethod("toString"); // This needs to catch NoSuchMethodException.
Method[] methods = new Method[] { toString };

However, in your example, you are working with functionalities that you can also put into an array:

Function<String, String> toStringFunc = String::toString;
Function[] funcs = new Function[] { toStringFunc };

java.lang.reflection.Method java.util.function.Function , .

, .

+1

You cannot create a shared array, but you can declare it (although there is a warning):

@SuppressWarnings("unchecked")
Function<String, Integer>[] arr = new Function[2];
arr[0] = String::length;
0
source

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


All Articles