Created
January 31, 2014 13:48
-
-
Save rsrini7/bc1c2c5aa7e23dee78c2 to your computer and use it in GitHub Desktop.
Callback method through reflection in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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