Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created December 4, 2012 23:33
Show Gist options
  • Save wjlafrance/4210258 to your computer and use it in GitHub Desktop.
Save wjlafrance/4210258 to your computer and use it in GitHub Desktop.
class MsgSend
{
/**
* Dynamically invoke a method, much like Objective-C message sending.
*
* This will ignore access restrictions, much like in Objective-C.
* Invoking private methods on other classes may cause harmful side-effects.
*
* @param object The object to "pass the message" to. If this is null,
* the result is always null.
* @param methodName String specifiying the name of the method, similar to
* Objective-C's selectors.
* @throws RuntimeException Exception thrown if no method exists for the
* specified arguments.
*/
public static Object msgSend(Object object, String methodName, Object... args)
{
if (object == null) {
return null;
}
Object returnObject = null;
Method method = null;
try {
Class[] argumentClasses = new Class[args.length];
for (int i = 0; i < args.length; i++) {
argumentClasses[i] = args[i].getClass();
}
method = object.getClass().getDeclaredMethod(methodName, argumentClasses);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
// Enable bypassing of access restrictions.
method.setAccessible(true);
try {
returnObject = method.invoke(object, args);
} catch (IllegalAccessException ex) {
// Should not happen due to access bypass.
ex.printStackTrace();
return null;
} catch (InvocationTargetException ex) {
ex.printStackTrace();
return null;
}
return returnObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment