This is doable, but only via a hack, so there's no guarantee it will work on each VM.
With that out of the way, here's how to do it:
1. Make your functional interface extend Serializable
:
@FunctionalInterface
public interface MyRPC extends Serializable {
Object execute(Object input);
}
Its instances will now have an internal method called writeReplace
that can be used to extract a SerializedLambda
that will contain metadata.
2. Extract the class/method info from SerializedLambda
(you can add the code to some utility class, or the functional interface itself):
@FunctionalInterface
public interface MyRPC extends Serializable {
Object execute(Object input);
default SerializedLambda serialized() {
try {
Method replaceMethod = getClass().getDeclaredMethod("writeReplace");
replaceMethod.setAccessible(true);
return (SerializedLambda) replaceMethod.invoke(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
default String getImplClassName() {
return serialized().getImplClass().replaceAll("/", ".");
}
default String getImplMethodName() {
return serialized().getImplMethodName();
}
}
3. Enjoy the fruits of your hackery:
public static Object invokeRpc(MyRPC rpc, Object input) {
System.out.println(rpc.getImplMethodName()); //
return rpc.execute(input);
}