This is a difficult case, since methods must return the object itself as Appendable and has an overloaded method name that does not work well with the groovy map for casting the interface. The easiest and most understandable way is probably just to use an anonymous inner class, as in Java. This requires a reasonably current groovy version (1.7 or newer, I think):
def testAppendable(Appendable appendable) { println "appendable = $appendable" appendable.append('a' as char). append('b' as char). append('c' as char) } testAppendable(new Appendable() { Appendable append(char c) { println "got $c" this } Appendable append(CharSequence csq) { this } Appendable append(CharSequence csq, int start, int end) { this } String toString() { "inner class appendable" } });
Another alternative would be to use Expando with closure. This is a bit inconvenient, since in the constructor you can initialize only one implementation per method name. Note that any skipped interface methods are set by default, which cause an exception.
testAppendable(new Expando( append: { char c -> println "got $c" delegate as Appendable }, toString: { -> "expando appendable" } ) as Appendable)
EDIT: As for your example, I don't understand why it will fail. My test is almost identical and works without any problems. What does the signature of process.consumeProcessOutput look like? Alternatively, you can double-check that MyClass$1 implements Appendable by running javap MyClass$1 .
source share