[ACCEPTED]-How to make a method which accepts any number of arguments of any type in Java?-argument-passing

Accepted answer
Score: 11

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

public void func(Object[] args) {
}

Or if you want to be able to pass 1 nothing:

public void func(Object... args) {
}
Score: 6
public void omnivore(Object... args) {
   // what now?
}

In Java, a variable of any reference type 8 (objects and arrays), including ones of 7 some generic type, even wildcards, can be 6 passed to a parameter of type Object. A 5 variable of any primitive type can be autoboxed 4 to its corresponding wrapper type, which 3 is a reference type, and so can be passed 2 as Object. So, Object... will accept any number of 1 anything.

Score: 4

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

0

Score: 2

The closest you will get is someMethod(Object ... args).

Strictly, this 6 does not accept all argument types. Specifically, it 5 does not accept primitive types: these need 4 boxed to the corresponding wrapper types. Normally 3 this makes no difference. But it does if 2 you need to distinguish between primitive 1 and wrapper types in the called method.

More Related questions