Skip to content

Instantly share code, notes, and snippets.

@rsrini7
Created January 31, 2014 13:48
Show Gist options
  • Select an option

  • Save rsrini7/bc1c2c5aa7e23dee78c2 to your computer and use it in GitHub Desktop.

Select an option

Save rsrini7/bc1c2c5aa7e23dee78c2 to your computer and use it in GitHub Desktop.
Callback method through reflection in java
package com.sriniproj.callback;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CallBack {
public static Object invoke(Object scope, String methodName,
Object... parameters) {
Object object = null;
Method method;
try {
method = scope.getClass().getMethod(methodName,
getParemeterClasses(parameters));
object = method.invoke(scope, parameters);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
@SuppressWarnings("unchecked")
private static Class[] getParemeterClasses(Object... parameters) {
Class[] classes = new Class[parameters.length];
for (int i = 0; i < classes.length; i++) {
classes[i] = parameters[i].getClass();
}
return classes;
}
}
package com.sriniproj.callback;
public class TestCallback {
public void test() {
TestClass testClass = new TestClass();
CallBack.invoke(testClass, "sayHello");
CallBack.invoke(testClass, "sayHello", "Polish","Witaj ");
CallBack.invoke(testClass, "sayHello", "French","Bonjour tout le monde ");
}
public static void main(String[] args) {
new TestCallback().test();
}
class TestClass {
public void sayHello() {
System.out.println("English :"+" Hello world!");
}
public void sayHello(String language, String words) {
System.out.println(language + " : " + words);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment