Last active
September 24, 2022 21:01
-
-
Save big-guy/33cc53284a8e81047cc73f37bc29bfe7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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