如何在 Java 中创建一个接受任意数量任意类型参数的方法?
我可以看到 Java 中有一种方法可以接受任意数量的指定类型的参数: http: //www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-am.html
但是有没有办法使一个接受任意数量任意类型参数的方法?
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-a-m.html
but is there a way to make a method which accepts any number of arguments of any type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
所有 Java 对象都扩展了 Object 类。所以你可以让你的函数接受一个对象数组:
或者如果你不想传递任何东西:
All Java Objects extend the Object class. So you can make your function accept an Object array:
Or if you want to be able to pass nothing:
在 Java 中,任何引用类型(对象和数组)的变量,包括某些泛型类型,甚至通配符,都可以传递给 Object 类型的参数。任何基本类型的变量都可以自动装箱为其相应的包装类型,该类型是引用类型,因此可以作为对象传递。因此,
Object...
将接受任意数量的任何内容。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. 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. So,
Object...
will accept any number of anything.使用这个语法:
Use this syntax:
您将得到的最接近的是
someMethod(Object ... args)
。严格来说,这不接受所有参数类型。具体来说,它不接受原始类型:这些类型需要装箱到相应的包装类型。通常这没有什么区别。但如果您需要在被调用方法中区分原始类型和包装类型,则需要这样做。
The closest you will get is
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.