Code, JavaEE

Invoke Methods on a Class using Reflection

This is useful if in this case all of the methods expect the same arguments/types.


public void invokeCUDMethodsOnClass(Object objectToUse, Map<String, Object> metaData) {

String[] methods = {"create", "update", "delete"}; // all the methods return void

for (String methodToInvoke : methods) {

try {
 Method methodToCall = objectToUse.getClass().getMethod(methodToInvoke, new Class[] { String.class, Map.class });
methodToCall.invoke(objectToUse, "request", metaData);
 } catch (NoSuchMethodException e) {
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 e.printStackTrace();
 }

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s