我可以将数组作为参数传递给 Java 中带有可变参数的方法吗?

编程入门 行业动态 更新时间:2024-10-24 06:31:45
本文介绍了我可以将数组作为参数传递给 Java 中带有可变参数的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够创建一个函数,例如:

class A {私人字符串 extraVar;public String myFormat(String format, Object ... args){返回 String.format(format, extraVar, args);}}

这里的问题是 args 在方法 myFormat 中被视为 Object[],因此是 的单个参数>String.format,而我希望 args 中的每个 Object 都作为新参数传递.由于 String.format 也是一个带有可变参数的方法,所以这应该是可能的.

如果这是不可能的,是否有类似 String.format(String format, Object[] args) 的方法?在这种情况下,我可以使用新数组将 extraVar 前置到 args 并将其传递给该方法.

解决方案

可变参数的基础类型

a> 方法 function(Object... args) is function(Object[] args).Sun 以这种方式添加了可变参数以保持向后兼容性.

所以你应该能够在 extraVar 前面加上 args 并调用 String.format(format, args).

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. Since String.format is also a method with variable arguments, this should be possible.

If this is not possible, is there a method like 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.

解决方案

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

So you should just be able to prepend extraVar to args and call String.format(format, args).

更多推荐

我可以将数组作为参数传递给 Java 中带有可变参数的方法吗?

本文发布于:2023-07-31 15:42:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260029.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   数组   方法   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!