强制使用数组调用解析为varargs调用

问题描述 投票:0回答:1

好,所以我有类似的功能

public static UnorderedList newUnorderedList(Object... items) {
    return new UnorderedList(
        stream(items)
            .peek(e -> checkNotNull(e, "Cannot create null list item"))
            .map(e -> {
                if (e instanceof Component) return newListItem((Component) e);
                if (e instanceof String) return newListItem((String) e);
                throw new IllegalArgumentException("List item must be String or Component but is neither: " + e.getClass().getName());
            }).toArray(ListItem[]::new)
    );
}

当您使用数组调用它时会触发警告,说不清楚是要将数组本身视为单个元素还是作为元素的容器。

不会立即看到一种优雅的方法。我都不喜欢这些:

  • 总是强制转换为Object[]
  • Object...变成Collection<Object>

是否存在注释或使编译器知道的总能始终将数组解析为带注释方法的vararg调用的注释? (在方法声明上,而不是在调用站点上。)

java casting jvm variadic-functions type-inference
1个回答
0
投票
您以错误的方式制作了UnorderedList。

假设它是一个集合:

© www.soinside.com 2019 - 2024. All rights reserved.