Re: Loop to handle many field condition statements
teser3@hotmail.com wrote:
Anyway I can create a loop to go through all
15 fields or how is the best way to do this??
NOTE: I do not have experience with beans, so there might be an
exception to my rules here. Soliciting advice from anyone with more
knowledge here to supersede me.
The best way is to internally store the fields as a HashMap and iterate
over that.
The second best way is to internally store the fields as a TreeMap and
iterate over that.
The third best way is to internally store the fields as anything else
that implements the Map interface and iterate over that.
The fourth best way is to manually go through each field.
There is a fifth way that I really don't recommend. Try using the first
method instead.
Still want to hear it?
This uses reflection:
Field[] fields = {< classname >}.class.getDeclaredFields();
for (Field f : fields) {
if (f.getType().getName().equals("java.lang.String")) {
errors.put(f.getName(),(String)f.get(this));
}
}
Like all reflection, that would have to be wrapped with a myriad of
exceptions; it is also prone to breaking if one is not careful (although
annotations would considerably help if this were being done). Finally,
it is also considerably slower than using a HashMap.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth