How to make a method which accepts any number of arguments of any type in Java?

妖精的绣舞 提交于 2019-12-23 11:40:43

问题


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?


回答1:


All Java Objects extend the Object class. So you can make your function accept an Object array:

public void func(Object[] args) {
}

Or if you want to be able to pass nothing:

public void func(Object... args) {
}



回答2:


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. 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.




回答3:


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.
}



回答4:


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.



来源:https://stackoverflow.com/questions/9354333/how-to-make-a-method-which-accepts-any-number-of-arguments-of-any-type-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!