You might want to define an interface for the loop body:
interface FieldOperation { void doSomeStuff(Field f); }
Then, instead of foo1 , foo2 and foo3 you can write one looping method:
public void foo(, FieldOperation op) { for (Field f : getClass().getDeclaredFields()) { op.doSomeStuff(f); } }
Then you can create several FieldOperation objects:
FieldOperation foo1Operation = new FieldOperation() { void doSomeStuff(Field f) {
This scales well and separates the logic of which fields are available for the operation that you want to perform in each field.
EDIT If each foo* requires a different set of arguments, I would suggest packing them as classes:
class Foo1Args { . . . } class Foo2Args { . . . } class Foo3Args { . . . }
Then you can make your general interface:
interface FieldOperation<T> { void doSomeStuff(Field f, T args); }
and define foo as a generic method:
public <T> void foo(T args, FieldOperation<T> op) { for (Field f : getClass().getDeclaredFields()) { op.doSomeStuff(f, args); } }
source share