gpt4 book ai didi

Java 如何将可变参数传递给另一个函数,如 Paths.get()

转载 作者:行者123 更新时间:2023-12-01 19:49:58 25 4
gpt4 key购买 nike

我正在尝试将可变参数传递给 Paths.get()

根据我的理解,可变参数本质上被解释为一个数组。但是 get() 方法需要单个字符串而不是一个字符串数组。

如何将可变参数传递给方法?

import java.nio.file.Path;
import java.nio.file.Paths;

public static Path getLogFilePath(String... stringArgs) {
int sLen = stringArgs.length;

Path path = Paths.get(stringArgs); // Cannot resolve method 'get(java.lang.String[])'
return path;
}

最佳答案

另一种做法是模仿 Paths.get() 原型(prototype):

public static Path getLogFilePath(String first, String... others) {
if( first == null) {
throw new IllegalArgumentException("Always a first String !!!");
}

Path path = Paths.get(first, others); // Compiles !
return path;
}

注意:Paths.get 故意使用两个参数来明确告诉用户至少需要一个字符串。在我看来,在其之上实现一个允许传递空数组的方法只是等待一个 RuntimeException

关于Java 如何将可变参数传递给另一个函数,如 Paths.get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com