Skip to content

Instantly share code, notes, and snippets.

@big-guy
Last active September 24, 2022 21:01
Show Gist options
  • Save big-guy/33cc53284a8e81047cc73f37bc29bfe7 to your computer and use it in GitHub Desktop.
Save big-guy/33cc53284a8e81047cc73f37bc29bfe7 to your computer and use it in GitHub Desktop.
interface Action<T> {
void execute(T t)
}
class ClosureBackedAction<T> implements Action<T> {
private final Closure closure;
ClosureBackedAction(Closure closure) {
this.closure = closure
}
public void execute(T delegate) {
try {
Closure copy = (Closure) closure.clone();
copy.setResolveStrategy(Closure.DELEGATE_FIRST);
copy.setDelegate(delegate);
if (copy.getMaximumNumberOfParameters() == 0) {
copy.call();
} else {
copy.call(delegate);
}
} catch (groovy.lang.MissingMethodException e) {
e.printStacktrace()
}
}
}
class Foo {
void configureFoo(Action<? super Foo> action) {
action.execute(this)
}
// Delete this method to see the failure
void configureFoo(@DelegatesTo(Foo.class) Closure c) {
configureFoo(new ClosureBackedAction(c))
}
String getName() { "foo" }
}
@groovy.transform.CompileStatic
def foo() {
new Foo().configureFoo {
println "hello ${name} from configureFoo"
}
}
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment