java - "Iterating" through methods -
let's i've got java object that's got among others following methods:
public string getfield1(); public string getfield2(); public string getfield3(); public string getfield4(); public string getfield5();
is there way iterate through these methods , call 'em following code?
string fields = ""; for(int = 1; <= 5; ++){ fields += object.(getfield+i) + " | "; }
thank upcoming ideas.
there way using reflection:
try{ method m= object.getclass().getmethod("getfield"+string.valueof(i), new class[]{}); fields+=(string)m.invoke(object); }catch(...){...}
however: business smells of bad coding practice! can't rewrite getfieldn()
methods this?
string getfield(int fieldnum)
you asking trouble creating numbered methods. remember reflection slow , should used when string-based method calls absolutely essential flow of program. use technique user-defined scripting languages have method by name. isn't case @ here, calls integer-indexed. should therefore keep integer parameter.
if legacy code , absolutely unable change bad coding, might better off creating new method getmethod(int)
above wrap existing methods, delegates numbered getmethodn()
methods.
Comments
Post a Comment