• Post Reply Bookmark Topic Watch Topic
  • New Topic

Runtime pick up of methods to be executed  RSS feed

 
amit bose
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

Is it possible to pick up the version of the method to be executed at Runtime.
e.g. If I have a class A with getX() and getY() methods.
But only at runtime I will know which getter to call i.e. getX() or getY().

Is is possible something like execute get + {from Runtime X/Y}
to be excuted in Java.

-Cheers
ab
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Reflection API has what you need. But the intro to the API says "First, a note of caution. Don't use the reflection API when other tools more natural to the Java programming language would suffice".

Could you describe the problem you're trying to solve? We might be able to suggest a more "object oriented" approach, perhaps with polymorphism instead of two method names.
 
amit bose
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I basically have a session Object say SObj in which various parameters set like:

SObj.setA("value of A");
SObj.setB("value of B");
SObj.setC("value of C");

Then I set the SObj in session using:

session.SetAttribute("Session Object", SObj);

Now my code requires getting just one of the parameters A or B or C from the session at a time.

So I have written a method like:

public String getSessionInfo(String sessionObjectName, String sessionAttributeName)
{

SessionObject o = (SessionObject)session.getAttribute(sessionObjectName);
String sessionValue = null;

If(sessionAttributeName.equals("A")
{
sessionValue = (String)o.getA(); //get the value from the respective getter.
return sessionValue;
}
//Similarly for B, C etc.
}


In the above method I invoke as;

String valueOfA = getSessionInfo("Session Object","A");


To make the method getSessionInfo( ) more generic and maintainable, instead of having the multiple
if loops (if there are 20 attributes, then 20 if loops are required) it is better to have something
like

sessionValue = (String)o.get + {From Runtime A/B/C()} ;


Hope the problem is clarified. If not, please revert.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like a job for Map. Are you familiar with the API for that? Things like:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!