2

Hi is there any way for me to pass variable arguments to a method?

public void unMarshalling(String type, int number){

}

So that instead of int, I can make my method such that I am able to pass in float, double, string and other primitive data types(+ string). Any simple examples will be deeply appreciated! Thanks alot!

2
  • 2
    you mean : variable number of arguments, or generic variable arguments (which can be anything)? Commented Mar 20, 2012 at 4:09
  • Maybe public void example(Object a){} could do it? Commented Mar 20, 2012 at 4:12

3 Answers 3

12

Try this:

public void unMarshalling(Object ... params) {

}

Now you can pass any number of arguments of any type:

unMarshalling(23);
unMarshalling("Hello");
unMarshalling("Hello", 45.3);
Sign up to request clarification or add additional context in comments.

Comments

0
public void unMarshalling(String a, int b){}
public void unMarshalling(String a, float b){}
public void unMarshalling(String a, double b){}
public void unMarshalling(String a, String b){}

It will know which one to call based on the type. If there's really only one function, you can put the 'meat' of it in String/int, then in String/float you can cast the float to an int as you like and call String/int.

public void unMarshalling(String a, float b)
{
  unMarshalling(a,(int)b);
}

Comments

0

Java has var-args functionality, this means you can pass any number of argument in var-args of given type example -

  public void myMethod(int...args)
 {
 }

you can call this as methods as below -

  myMethod(3);

or myMethod(3,4);

or myMethod(3,65,74); and so on.

You can specify any type of argument besides int.

please keep var-args as last argument if you have more then one argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.