Arvind Carpenter
Arvind Carpenter

Reputation: 48

Calling Method at runtime using some string

I am new to these and I need a solution or idea how I can do it

I have the following code:

if (page.getId().equals("STEP_NAME_SUBMIT_OTP_FOR_TRANSACTION"))
    emRequestResponse.setTagElementList(agent.getHeader().getTagElementList().getSTEP_NAME_SUBMIT_OTP_FOR_TRANSACTION());
else if (page.getId().equals("STEP_NAME_SUBMIT_CAPTCHA_FOR_LOGIN"))
    emRequestResponse.setTagElementList(agent.getHeader().getTagElementList().getSTEP_NAME_SUBMIT_CAPTCHA_FOR_LOGIN());

I need a better way to call the method at run time based on the id, so if the name is STEP_NAME_SUBMIT_OTP_FOR_TRANSACTION I need to call the method getSTEP_NAME_SUBMIT_OTP_FOR_TRANSACTION and so on.

Upvotes: 1

Views: 82

Answers (3)

kakkarot
kakkarot

Reputation: 23

The answer to your question is the REFLECTION API of java.

I would recommend using switch case for your strings, because, as per your requirement, I see that the Strings can be made final.

And using the Method class, you can invoke methods by populating the method name and required arguments.

The following block of code should do the trick for you, assuming the methods you want to call are defined in a class named TagElementsList.

private List invokeMethod(TagElementsList tagElementsList, String pageId) {
    Method method = TagElementsList.class.getMethod("get"+pageId);
    List returnList = (TagElementsList)method.invoke(tagElementsList);
    return returnList;
}

You can thus get the method working as per your needs by invoking a call to the invokeMethod method from the required location in your code by the following call, considering the above method is declared in the same class as the point from where it has to be invoked. You can of course put define it in a different class and invoke a call to the method via an instance of that class too.

List list = invokeMethod(agent.getHeader().getTagElementList(), page.getid());
 emRequestResponse.setTagElementList(list);

Upvotes: 0

Dark Knight
Dark Knight

Reputation: 8347

You may use switch over if-else, switch performs better than if-else.

Switch performance will be better as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.

In case of large number of conditions, better will be switch performance but for shorter list (just two conditions), it can be slower also

Upvotes: 0

Chetan Joshi
Chetan Joshi

Reputation: 5711

You can call method like below code:

try {
Method method = emRequestResponse.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);
} catch(Exception ex) {
System.out.println(ex.toString());
}

Upvotes: 2

Related Questions