Last Updated: February 25, 2016
·
4.179K
· bazlur_rahman

How to implement callback method in java using java reflection?

There are many ways to implement the callback method in Java, like –

Some use observer pattern to solve callback problem, some use .net delegate like anonymous method in java. Here I have found a way to implement callback using java reflection. I think it’s a quite good way.

[code]
package org.codexplo.util.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 | SecurityException
 | InvocationTargetException | IllegalAccessException e) {
 e.printStackTrace();
 }
 return object;
 }
 @SuppressWarnings("rawtypes")
 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;
 }
}
[/code]

Test Cases

[code]

package org.codexplo.util.callback;

import org.junit.Test;

public class TestCallback {
 @Test
 public void test() {
 TestClass testClass = new TestClass();
 CallBack.invoke(testClass, "sayHello");
 CallBack.invoke(testClass, "sayHello", "Polish","Witaj świecie ");
 CallBack.invoke(testClass, "sayHello", "Arabic","مرحبا العالم ");
 CallBack.invoke(testClass, "sayHello", "French","Bonjour tout le monde ");
 CallBack.invoke(testClass, "sayHello", "Chinese","你好世界 ");
 }

class TestClass {
 public void sayHello() {
 System.out.println("English :"+" Hello world!");
 }

public void sayHello(String language, String words) {
 System.out.println(language + " : " + words);
 }
 }
}

[/code]

nice shoot!

if you like my post, you may visit my blog:

https://codexplo.wordpress.com/
http://blog.codexplo.org/

1 Response
Add your response

I really don't understand what you are doing here. I mean, you have access to the class you want to callback, you know the method and parameters. Why not just call testClass.sayHello(..) as one normally would?

When i hear "callback" I presume A calls B to do something, then expects B to "callback" to A upon some condition. I don't really see that happening here.

Maybe B doesn't really know what A really is. Well its going to need to at least know the method name and parameters. Why not just use polymorphism constructs built into Java for that?

over 1 year ago ·