Skip to content

Instantly share code, notes, and snippets.

@Mukundhan-I2I
Created September 9, 2019 10:42
Show Gist options
  • Save Mukundhan-I2I/dd61d5cdafacfd91716e658f86a06d0d to your computer and use it in GitHub Desktop.
Save Mukundhan-I2I/dd61d5cdafacfd91716e658f86a06d0d to your computer and use it in GitHub Desktop.
Generic method call using reflection
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