[英]How to make a method which accepts any number of arguments of any type in Java?
I can see there is a way to have a method in Java which accepts any number of arguments of a specified type: http://www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-am.html 我可以看到在Java中有一种方法可以接受任意数量的指定类型的参数: http : //www.java-tips.org/java-se-tips/java.lang/how-to-传递非指定数的论点对am.html
but is there a way to make a method which accepts any number of arguments of any type? 但有没有办法使一个方法接受任何类型的任何数量的参数?
All Java Objects extend the Object class. 所有Java对象都扩展了Object类。 So you can make your function accept an Object array:
所以你可以使你的函数接受一个Object数组:
public void func(Object[] args) {
}
Or if you want to be able to pass nothing: 或者如果你想要什么都不通过:
public void func(Object... args) {
}
public void omnivore(Object... args) {
// what now?
}
In Java, a variable of any reference type (objects and arrays), including ones of some generic type, even wildcards, can be passed to a parameter of type Object. 在Java中,任何引用类型(对象和数组)的变量(包括某些泛型类型的变量,甚至通配符)都可以传递给Object类型的参数。 A variable of any primitive type can be autoboxed to its corresponding wrapper type, which is a reference type, and so can be passed as Object.
任何基本类型的变量都可以自动装箱到其相应的包装类型,这是一种引用类型,因此可以作为Object传递。 So,
Object...
will accept any number of anything. 因此,
Object...
将接受任何数量的任何东西。
Use this syntax: 使用以下语法:
void myMethod(Object... args) {
// Here, args is an array of java.lang.Object:
// you can take its length, get its elements with [i] operator,
// and so on.
}
The closest you will get is someMethod(Object ... args)
. 你得到的最接近的是
someMethod(Object ... args)
。
Strictly, this does not accept all argument types. 严格来说,这不接受所有参数类型。 Specifically, it does not accept primitive types: these need boxed to the corresponding wrapper types.
具体来说,它不接受原始类型:这些需要装入相应的包装类型。 Normally this makes no difference.
通常这没有区别。 But it does if you need to distinguish between primitive and wrapper types in the called method.
但是如果你需要区分被调用方法中的原始类型和包装类型,它就会这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.