Pages

Tuesday, July 17, 2012

java invoke methods by a string name.

Let's assume that you have a string value and the method name also have the same name as the string value. If you want to invoke the the method using the
string value you can do it like this,

Object obj;//object class which the method has
String methodName = "getName" //string that you need to invoke the method.
 
THEN GET THE METHOD LIKE THIS
 
java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}
 
AFTER THAT YOU CAN INOKE IT LIKE THIS
 
try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} 
 

No comments:

Post a Comment