Search code examples
groovyjenkinsself-referenceloopback

Groovy - Is there a way to ask an object to return itself?


Let's say I have some object in groovy called obj. Is there a default method or property that I can call on obj that will return give me back that object? For example:

def obj = new Whatever()
assert obj == obj.self

Context: I am scripting within the context of the ClosureScript class defined within Jenkins. This is an extension of the Script class that allows delegation-type workflows. Unfortunately, it works by just forwarding getProperty() and invokeMethod() calls to the delegate, it doesn't expose a direct reference to the delegate object itself. So a self-referencing property/method would allow me to get that reference.


Solution

  • So I ended up finding a way to do this. In the default groovy methods, there are a few methods that you can effectively turn into no-ops. For example:

    assert obj == obj.find()
    assert obj == obj.each{it}
    

    will both pass.

    Unfortunately, this didn't actually solve my original problem. The delegation strategy in that Script class I was using ends up calling the default method on the script first before the delegate. This does answer the question as I asked it, though, so I'll just close it and move on.