[英]Passing byte[] as a single parameter to a vararg method
I have a method which has a varargs parameter.我有一个方法,它有一个 varargs 参数。 It looks like this:它看起来像这样:
public void sampleFunction(String name, Object... args) {
}
I want to pass a byte[]
to this method, but as a single parameter.我想将byte[]
传递给此方法,但作为单个参数。 How can I do this?我怎样才能做到这一点?
byte[] myByteArray = functionReturningAByteArray();
sampleFunction("Name", myByteArray);
Will this be considered as an array or, will myByteArray
is considered as a single object?这会被视为一个数组,还是将myByteArray
视为单个对象?
When I passed the byte[]
, IntelliJ reports it as Confusing primitive array argument to varargs method
.当我传递byte[]
,IntelliJ 将其报告为Confusing primitive array argument to varargs method
。 I tried to cast myByteArray
to an Object
as it suggested, then it reports it as redundant cast.我试图按照它的建议将myByteArray
为一个Object
,然后它将其报告为冗余转换。
I want to pass it as a single object.我想将它作为单个对象传递。
A byte[]
is a primitive array, so it is definitely not an Object[]
. byte[]
是一个原始数组,所以它绝对不是一个Object[]
。 Therefore, it will be passed as a single Object
instance to your vararg method.因此,它将作为单个Object
实例传递给您的 vararg 方法。
If, on the other hand, you would pass a Byte[]
array, it will be passed as multiple Object
arguments to the vararg method.另一方面,如果您要传递一个Byte[]
数组,它将作为多个Object
参数传递给 vararg 方法。
Of course, you can verify this for yourself:当然,你可以自己验证一下:
public static void sampleFunction(String name, Object... args) {
System.out.println (args.length);
}
sampleFunction("x", new byte[] {1,2,3});
sampleFunction("x", new Byte[] {1,2,3});
The first call prints 1
, while the second call prints 3
.第一个调用打印1
,而第二个调用打印3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.