It's a simple and maybe trivial question: in Java h开发者_开发知识库ow 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?
If your function uses Varargs this is pretty straightforward:
private void yourFunction(String... parameters) {
for (String parameter : parameters) {
// Do something with parameter
}
}
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.
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)
For you can change your method to be the following you can iterate over them.
public void method(String... args)
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!
}
精彩评论