tanapoln
tanapoln

Reputation: 529

Groovy: Delegate instance method to meta class

I'm findind a way easier to implement this kind of feature:

RESTClient client = new RESTClient("https://api.github.com", JSON)
class CoreApi {}
RESTClient.methods*.name.each { name ->
  if (! CoreApi.methods.contains(name)) {
    CoreApi.metaClass.static."$name" = {Object... args -> client."$name"(*args)}
  }
}

and then we can use CoreApi.get(path: "/users/your-user")

Is there any annotation available in groovy for implement this kind of behaviour? What's it called?

Upvotes: 0

Views: 105

Answers (1)

Sergey Tselovalnikov
Sergey Tselovalnikov

Reputation: 6036

You are looking for @Delegate

class CoreApi {
    @Delegate RESTClient client
}

But it doesn't work for static methods

Static methods, synthetic methods or methods from the GroovyObject interface are not candidates for delegation

Upvotes: 2

Related Questions