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.
// returns String: 'boo'
First, we create
Methrefobject and call method
nameon method reference. Could it be simpler?
If a method has arguments, just pass whatever: usually
Methref.of(Str.class).name((str) -> str.hello(null, 0));
// returns 'hello'
Two important things to remember:
- 1.Although there is a target method invocation, method code is NOTexecuted! Proxy just returns
nullor a method name if methods return type is a
- 2.Create new
Methrefwhere 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 proxy
Str str = m.proxy();
// invoke method
// get invoked method name
String 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
Methrefin 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
Methreffrom 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.