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.


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;
 }
}

Test case


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);
 }
 }
}

nice shoot! 😀 😀

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