12

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?

bluish
  • 26,356
  • 27
  • 122
  • 180
  • How you method declaration looks like? – Mot Dec 10 '10 at 10:54
  • 2
    why you need them? if you know the name of parameters then you can do that on very top in your method. – Singleton Dec 10 '10 at 10:55
  • 2
    My method is a simple constructor with many fields, but the question is valid for any method, in wich I want to do something with all parameters. It would be useful to write simple and elegant code and not to change it every time you add/modify/delete a parameter. – bluish Dec 10 '10 at 10:59

5 Answers5

11

If your function uses Varargs this is pretty straightforward:

private void yourFunction(String... parameters) {
  for (String parameter : parameters) {
    // Do something with parameter
  }
}
David
  • 3,787
  • 2
  • 29
  • 43
  • 1
    ... as long as the strings the OP is talking about _should_ be thought of as a group. The OP shouldn't pack them together simply for the sake of being able to conveniently being able to iterate through them. – Bert F Dec 10 '10 at 11:04
  • 1
    I can't use this because my parameters need a different name each one. Using an array or similar would complicate the situation. – bluish Dec 10 '10 at 11:05
7

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 1
    Thanks! Since now your answer seems the most correct, even if disillusioned :) However my method is a constructor, I pass to it a lot of fields that have to be saved in a DB record. I'm wondering: what's a "shovel"? Never heard it associated with Java.. – bluish Dec 17 '10 at 13:42
  • 6
    "get a shovel" is an expression that means "roll up your sleeves and get to work". It usually comes out when a developer is faced with a large, tedious task that requires long effort and patience to complete rather than brute brain power. – duffymo Dec 17 '10 at 16:07
3

The task you are trying solve is only possible using AOP (Aspect Oriented Programming) frameworks.

AOP frameworks allow you to add some code to the method without changing it. In reality they create Proxy classes that wrap around your original classes and execute required lines of code before each method you bind them too.

However, AOP is an overkill for some simple tasks as it usually requires some complex configurations and usually integration with DI frameworks.

Here's some list of AOP frameworks if you are still interested: http://java-source.net/open-source/aspect-oriented-frameworks.

Edit:

Actually, I think that you are doing your task the wrong way in first place. If your method is a part of Business Layer - it should not allow non-trimmed parameters and throw some kind of Exception in that case. If your method is part of some Presentation Layer - it should be cleaning the parameters manually, usually near the part where it reads the parameters from the user.

For example, if you are reading that parameters from some Swing form, then you should trim them before passing to your Constructor. For example:

Your current code:

int someId = Integer.valueOf(idField.getText());
String someName = nameField.getText();
String someArg = argField.getText();
new Constructor(someId, someName, someArg)

How it should be handled:

int someId = Integer.valueOf(idField.getText());
String someName = nameField.getText().trim();
String someArg = argField.getText().trim();
new Constructor(someId, someName, someArg)
bezmax
  • 25,562
  • 10
  • 53
  • 84
  • Your edit part it's a good observation, thanks! However I'd like to find a way to do exactly what I said.. it's like a challenge vs Java ;) – bluish Dec 10 '10 at 13:11
  • Well, if you want it easy - Java can not do that. You can't iterate over method parameters. Moreover, you can not access local variables with reflection either. So the only thing you can do is AOP or something similar which can control all calls to specific method of a class. – bezmax Dec 10 '10 at 13:24
0

For you can change your method to be the following you can iterate over them.

public void method(String... args)
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    ... as long as the strings the OP is talking about should be thought of as a group. The OP shouldn't pack them together simply for the sake of being able to conveniently being able to iterate through them. – Bert F Dec 10 '10 at 11:05
  • Little nicer but also epically failing solution would be to pass a Map of parameters and iterate over it :) – bezmax Dec 10 '10 at 11:19
  • @Bert, this is true. However needing to trim() all Strings suggested it might be a group of Strings. – Peter Lawrey Dec 10 '10 at 11:27
  • absolute agreement - not a nit for your answer - you beat me to that same answer :). I just wanted to contribute a consideration for a potentially overzealous OP. – Bert F Dec 10 '10 at 13:13
  • @Bert, it was worth mentioning. – Peter Lawrey Dec 10 '10 at 13:45
0

If your question is how to recognise a String from an Object, you can do that:

if (myObject instanceof String) {
  // My param is a string!
}
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124