Methref is a tool that gives you strong-type references to method names.
Sometimes you need to refer to a method in our code using their names. Usually, in this cases, method names are stored as strings and they are not immune to method name changes and typing errors.
Methref is a tiny and cool utility, build on Proxetta, that provides strongly-typed references to method names. Here is how it works.
Methref.of(Str.class).name(Str::boo);// returns String: 'boo'
First, we create
Methref object and call method
name on method reference. Could it be simpler?
If a method has arguments, just pass whatever: usually
null or zeros:
Methref.of(Str.class).name((str) -> str.hello(null, 0));// returns 'hello'
Two important things to remember:
Although there is a target method invocation, method code is NOT
executed! Proxy just returns
null or a method name if methods return type is a
Methref where needed. However, they can be stored and reused.
With Methref you can actually do a lot of magic :) Previous, simple usage can be split into several steps:
Methref m = Methref.of(Str.class);// get proxyStr str = m.proxy();// invoke methodstr.foo();// get invoked method nameString name = m.lastName();
This approach is made for cases when method invocation happens in different place of your code, where you don't want to expose
Imagine that you are creating several
Methref in one place of code. Then, a user of your code will call a method on one of those proxies, but you don't have control over which. There is a way to detect the
Methref from the proxy by calling method
isMyProxy. Furthermore, there is a
lastName(instance) that works like the
As I said, it can be used for magic :) Believe it or not, with Methref you can create, for example, strongly typed SQL-alike syntax directly with your code.