Ideally I'd like to be able to express the idea: "whatever would be called by foo()
in the current position in the code, give me a method reference to foo
".
Rationale: I'm working on some code that uses a lot of high-order functions and function composition. I'd like: a) it to be as terse as possible, and b) not to have to keep editing class names scattered around the code as I refactor and move functions between classes.
For example:
/* ---- foo.pkg1.Utils.groovy */
public final class Utils {
private Utils() { /* as it's all static methods */ }
static foo() { 42; }
}
/* ---- foo.pkg2.Client1.groovy */
import foo.pkg1.Utils
def f1 = Utils.&foo // <-- restates class (but works)
println f1()
/* ---- foo.pkg2.Client2.groovy */
import static foo.pkg1.Utils.*
def f2 = foo // <-- No!
// "groovy.lang.MissingPropertyException: No such property: foo ..."
println f2()
def f3 = &foo // <-- No!
// "unexpected token: & at line: 17, column: 14"
println f3()
def f4 = this.&foo // <-- Also no!
// "groovy.lang.MissingMethodException: No signature of method..."
println f4()
/* ---- foo.pkg2.Client3.groovy */
/* My best attempt ... but this only allows me to change which
class 'u' refers too, not to create a method reference to
whatever `foo()` would call at the same place in the code. */
import static Utils as u
def f5 = u.&foo
println f5()
Slightly error-prone due to variable naming being bounded to
with
order, but it is something:Handling the script's own
binding
using reflection onUtil
class is also an option if you always use scripts.