Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through method parameters

It's a simple and maybe trivial question: in Java how can I iterate through the parameters passed to the method where I'm working?

I need it to trim() all of them that are strings.

EDIT

To be more precise an example of use can be this (written in a pseudo-code reflecting how I wish it to work):

public void methodName(String arg1, int arg2, int arg3, String arg4, double arg5)
    for(Object obj : getThisMethod().getParameters() )
        System.out.println(obj.getName() + " = " + obj.toString())

The point is that getThisMethod().getParameters(). What must I write in that place?

like image 900
bluish Avatar asked Dec 10 '10 10:12

bluish


2 Answers

If your function uses Varargs this is pretty straightforward:

private void yourFunction(String... parameters) {
  for (String parameter : parameters) {
    // Do something with parameter
  }
}
like image 160
David Avatar answered Sep 19 '22 06:09

David


Individual parameters aren't iterable; you'd need a collection for that.

You'll just have to get a shovel if they're individual Strings.

If you have so many String parameters that this is oppressive, perhaps your method needs to be re-thought. Either all those parameters should be encapsulated into an object, because they're related, or that method is trying to do too much. It speaks to a lack of cohesion to me.

like image 25
duffymo Avatar answered Sep 21 '22 06:09

duffymo