6

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?

flea whale
  • 1,783
  • 3
  • 25
  • 38

4 Answers4

11

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) {
}
Jivings
  • 22,834
  • 6
  • 60
  • 101
6
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.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
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.
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • thanks for you reply. Actually, I'm experimenting with your suggested `someMethod(Object...args)` and there seems to be no problem passing both primative and object types. I have used this as a test and get no errors: `someMethod(99, 1.23, "A String", new String("A Wrapper String"), anObject);` but maybe Java is wrapping the primatives up for me, who knows :) – flea whale Feb 19 '12 at 23:42
  • 1
    @fleawhale - It **is** wrapping them for you (autoboxing). But my point is that the called method cannot distinguish the cases where the caller provided a primitive value that was autoboxed from the case where it explicitly supplied the wrapper object. – Stephen C Feb 21 '12 at 00:04