Jakub Bochenski
Jakub Bochenski

Reputation: 3271

Anonymous class with methodMissing

For a DSL I'm writing I'd like to sometimes return a dummy object that just ignores all the calls.

This works:

class Dummy {
    def methodMissing(String name, args) { print "Ignoring: "+name+" "+args }
}

def foo(guardCondition) {

    if (guardCondition)
        return new Dummy()

    // ...
}

foo(true).with { bar('baz') }

but if I try to use an anonymous class the result is an error like No signature of method: <filename>.bar() is applicable for argument types: (java.lang.String) values: [baz]

Namely this doesn't work:

    if (guardCondition)
        return new Object() { def methodMissing(String name, args) { print "Ignoring: "+name+" "+args } }

neither does a "bag" approach work:

    if (guardCondition)
        return [ methodMissing : { name, args -> print "Ignoring: "+name+" "+args } ]

Upvotes: 1

Views: 229

Answers (1)

J&#233;r&#233;mie B
J&#233;r&#233;mie B

Reputation: 11022

There is an open issue about this : GROOVY-4862. In fact, it doesn't work in a inner class, anonymous or not.

Upvotes: 3

Related Questions