简体   繁体   English

Java如何将varargs传递给另一个函数,例如Paths.get()

[英]Java how can I pass varargs to another function like Paths.get()

I'm trying to pass varargs to Paths.get() 我正在尝试将varargs传递给Paths.get()

From my understanding, varargs essentially interpreted as an array. 根据我的理解,varargs本质上解释为数组。 But get() method expects individual String's not one String array. 但是get()方法期望单个String不是一个String数组。

How can I pass the varargs through to the method? 如何将varargs传递给方法?

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

您将必须显式处理第一个参数的分离:

Path path = Paths.get(stringArgs[0], Arrays.copyOfRange(stringArgs, 1, sLen);

Another take on this would be to mimic the Paths.get() prototype : 对此的另一种做法是模仿Paths.get()原型:

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

NOTE : Paths.get uses two arguments on purpose to explicitely tell users that at least one String is needed. 注意: Paths.get使用两个参数来明确告诉用户至少需要一个String。 Implementing a method above it that allows to pass an empty array is, in my opinion, just a RuntimeException in waiting. 我认为,在其上方实现允许传递空数组的方法只是等待中的RuntimeException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM