Wednesday, May 19, 2010

How to invoke a method in java using Reflection

// somehow you have an Object ; this is to invoke a method without Arguments
Class c = anObject.getClass();
Method method = c.getDeclaredMethod("theMethodWithNoArguments");
method.invoke(anObject);

//this is to invoke a method with Arguments
Class aClass = anObject.getClass();

//parameter types
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class;

//parameter values
Object[] params = new Object[1];
params[0] = "param1";

try {
Method m = aClass.getMethod("getDTO", paramTypes);
String result = (String)m.invoke(anObject, params);
} catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
}