Can I pass an array as arguments to a method with variable arguments in Java?

問題:

I'd like to be able to create a function like:我希望能夠創建一個函數,如:

class A {
  private String extraVar;
  public String myFormat(String format, Object ... args){
    return String.format(format, extraVar, args);
  }
}

The problem here is that args is treated as Object[] in the method myFormat , and thus is a single argument to String.format , while I'd like every single Object in args to be passed as a new argument.這裏的問題是args在方法myFormat被視爲Object[] ,因此是String.format的單個參數,而我希望args每個Object作爲新參數傳遞。 Since String.format is also a method with variable arguments, this should be possible.由於String.format也是一個帶有可變參數的方法,這應該是可能的。

If this is not possible, is there a method like String.format(String format, Object[] args) ?如果這是不可能的,是否有類似String.format(String format, Object[] args) In that case I could prepend extraVar to args using a new array and pass it to that method.在這種情況下,我可以使用新數組將extraVarargs並將其傳遞給該方法。


解決方案:

參考一: https://en.stackoom.com/question/CGxt
參考二: https://stackoom.com/question/CGxt
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章