user3316027 user3316027 - 1 year ago 76
Java Question

Variable method reference in java 8

I am trying to create a method reference with the variable, which holds method name for some method from an object:

SomeClass obj = new SomeClass();
String methodName = "someMethod";

I am looking for way to create exactly
, but using variable methodName for this. Is it possible?

I know how to create functional interface instance from

() -> {
try {
return obj.getClass().getMethod(methodName).invoke(obj);
} catch (NoSuchMethodException | IllegalAccessException e) {
return null;

but I am wondering is this can be done in more shorthand way.

Answer Source

This is a very rare case - it's highly unlikely that the Java8 syntax sugar has been optimised for this. In particular, it would be impossible for the usual compile-time type checking to occur (remember that a method reference is just syntax sugar for an anonymous class that adheres to a particular type contract).

If this pattern is common in your codebase (hopefully it's not!), you could just move it to, say, a static utility method, and then do () -> Utils.invoke(obj, methodName).