Dynamic Method Calls

84 Views Asked by At

From what I understand, methods can be dynamically called if both the method name and list of parameter types are provided (see below). However, is there a way to dynamically call a method without specifying parameter types or alternatively providing un/bounded generic class types? If yes, explanations/examples would be appreciated. Thanks.

Class<?>[] paramTypes = {String.class};
Method m = original.getClass().getMethod(methodName, paramTypes);
m.invoke(original, value);
2

There are 2 best solutions below

0
On BEST ANSWER

There is a solution since Java 1.4, Statement and Expression of the beans package. For your invocation, not evaluating return values, you can use

new Statement(original, methodName, new Object[]{value}).execute();

Since it has to figure out even more than the direct Reflection usage, you can expect the performance to be even worse than directly using Reflection.

Further, it is restricted to public APIs.

0
On

If you want to dynamically lookup the target method based on a target, a name and available argument types then the MethodHandle machinery might prove useful.