问题
I know how to declare an array of other things, like strings, in this way:
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 having to create a list and add every item individually.
Example: Call the method smartListMerge
on several diferent
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 right way to declare an array of method references?
回答1:
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);
回答2:
In your question, you asked of an array of methods. You can define it like this:
Method toString = String.class.getMethod("toString"); // This needs to catch NoSuchMethodException.
Method[] methods = new Method[] { toString };
Yet, in your example you work with functionals, which you can also put into an array:
Function<String, String> toStringFunc = String::toString;
Function[] funcs = new Function[] { toStringFunc };
Keep in mind to import java.lang.reflection.Method
for the first or java.util.function.Function
for the second example, respectively.
As far as I know, there is no shorthand for defining a list.
回答3:
You can't create a generic array, but you can declare one (there is warning though):
@SuppressWarnings("unchecked")
Function<String, Integer>[] arr = new Function[2];
arr[0] = String::length;
来源:https://stackoverflow.com/questions/49234884/how-to-declare-an-array-of-method-references