Friday, February 26, 2010

Java's equivalent to Javascript's eval()

I had a situation in my code where I needed to dynamically execute a method based on a String I received from some other method. The string specified the method name I had to execute.
The easiest option was to put in an "if...else" block and do string comparison. However, that's not the cleanest way. I was looking for a way in Java to imitate javascripts eval behavior.
Reflection came to my rescue. Here's how you can dynamically invoke methods in your code:

Example A - Invoking a method that does not have any parameter
Assume you need to call method methodA() in class com.examples.Myclass

Class c = Class.forName("com.examples.Myclass");
Object objMyclass = c.newInstance();
Method m = c.getMethod("methodA", null);
m.invoke(objMyclass , null);


Example B - Invoking a method that accepts a String parameter and returns a String
Assume you need to call method methodB(String param1) in class com.examples.Myclass

Class[] clazzez = new Class[1];
clazzez[0] = Class.forName("java.lang.String");
Object[] params= new Object[1];
params[0] = "Parameter Value";

Class c = Class.forName("com.examples.Myclass");
Object objMyclass = c.newInstance();
Method m = c.getMethod("methodB", clazzez);

String return = (String)m.invoke(objMyclass, params);


In both the examples you need to handle the appropriate exceptions. For more reference, refer to package Reflection APIs and you can also check out these examples.

Let me know if you get stuck somewhere or come up with some other challenges.

No comments: