Created
September 9, 2019 10:42
-
-
Save Mukundhan-I2I/dd61d5cdafacfd91716e658f86a06d0d to your computer and use it in GitHub Desktop.
Generic method call using reflection
This file contains 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
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Modifier; | |
import java.util.HashMap; | |
https://stackoverflow.com/questions/6680674/can-a-java-class-add-a-method-to-itself-at-runtime | |
public class GenericClass { | |
private HashMap<String, Method> methodMap = new HashMap<String, Method>(); | |
public Object call(String methodName,Object ...args) | |
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { | |
Method method = methodMap.get(methodName); | |
return method.invoke(null, args); | |
} | |
public void add(String name,Method method){ | |
if(Modifier.isStatic(method.getModifiers())) | |
methodMap.put(name, method); | |
} | |
public static void main(String[] args) { | |
try { | |
GenericClass task = new GenericClass(); | |
task.add("Name",Object.class.getMethod("Name", new Class<?>[0])); | |
} catch (NoSuchMethodException | SecurityException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment