Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Add arguments to the method @ Runtime

 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In JAVA is it possible to add arguments in methods @ Runtime? Please provide me reason also.
 
Wim Vanni
Ranch Hand
Posts: 96
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In what situation would you want that?

It is possible to have an undefined number of arguments if you make use of arrays (or collections).

Cheers
Wim
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or use varargs, available since Java 5.0. These arguments must be all of the same type (or at least have a common super type), the varargs parameter must be the last parameter of the method, and there can be only one varargs parameter per method. Inside the method you treat the parameter as if it's an array. For instance:
 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wim Vanni wrote:In what situation would you want that?

It is possible to have an undefined number of arguments if you make use of arrays (or collections).

Cheers
Wim



Actually i was asked this question in interview, so even i don't have any idea that in what type of situation they want.

Thanks Wim....
 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Or use varargs, available since Java 5.0. These arguments must be all of the same type (or at least have a common super type), the varargs parameter must be the last parameter of the method, and there can be only one varargs parameter per method. Inside the method you treat the parameter as if it's an array. For instance:


Thanks for the reply Rob.

The Same answer came into my mind. But if there are different types of arguments and we want to add another different type of argument.
e.g. void TestMethod(int arg1, char arg2) and what if i want to add string argument at runtime (e.g. void TestMethod(int arg1, char arg2, String arg3))

what i think is it's not possible but even i want to clear this confusion.

Thanks again.
 
Wim Vanni
Ranch Hand
Posts: 96
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Should work, no?

The toughtest part is having code that is dynamis enough to handle them, I guess.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic