【问题标题】:How to declare an array of method references?如何声明方法引用数组?
【发布时间】:2018-03-12 20:32:34
【问题描述】:

我知道如何用这种方式声明其他东西的数组,比如字符串:

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

但是当涉及到方法引用时,我不知道如何避免 创建一个列表并单独添加每个项目。

例子:在几个不同的地方调用smartListMerge方法 来自两个来源的匹配列表:

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);
}

声明方法引用数组的正确方法是什么?

【问题讨论】:

  • 你想要一个列表还是一个数组?

标签: java java-8


【解决方案1】:

创建列表的方法更短:

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

或(在 Java 9 中):

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

【讨论】:

  • What is the right way to declare an array of method references - OP 询问,List#ofArrays#asList 答案:) +1,但仍然很有趣
【解决方案2】:

在您的问题中,您询问了一系列方法。你可以这样定义:

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

然而,在您的示例中,您使用的是泛函,您也可以将其放入数组中:

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

请记住分别为第一个示例导入 java.lang.reflection.Method 或为第二个示例导入 java.util.function.Function

据我所知,没有定义列表的简写。

【讨论】:

  • Function[] funcs 应该触发警告
【解决方案3】:

你不能创建一个通用数组,但是你可以声明一个(虽然有警告):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多