mercredi 6 avril 2016

Java dynamically invoke method which is dynamically attached (by dynamic proxy) on an object

I have a method which has arguments an object instance and a string which represents the name of a method, with the following signature:

Object executeDynamicMethod(Object instance, String methodName);

I can easily execute the method by name by using reflection, something like the following:

Method methodToExecute = instance.getClass().getMethod(methodName...);
methodToExecute.invoke(); ...

However, what happens when the instance is a proxied one, and the method is running though an invocation handler? Then the instance object Class here has not the method and I can not get it and invoke it. Additionally, I don't want to use Proxy.getInvocationHandler(instance) because sometimes the instance is proxied, but sometimes not, and I don't want to spoil it with if statements.

Thus, is there any way to invoke a method by its name on an instance without having to retrieve the method from the class first? Thanks.





Aucun commentaire:

Enregistrer un commentaire