title: How to dynamically add all methods of a class into another class
body: <p>I have a <a href="https://jenkins.io/doc/book/pipeline/shared-libraries/#global-shared-libraries" rel="nofollow noreferrer">global shared library on Jenkins</a> implicitly loaded on all pipelines, then my <code>Jenkinsfile</code> is like that:</p>
  
  
  
  <pre><code>new com.company.Pipeline()()
  </code></pre>
  
  <p>And then the shared library has on directory <code>src/com/company</code> some files, below the <code>Pipeline.groovy</code> class:</p>
  
  <pre><code>package com.company  
  
  import static Utils.*
  
  def call() {
    // some stuff here...
  }
  </code></pre>
  
  <p>The problem is, this way I have to static declare all methods, thus I lose the context and cannot access jenkins' methods easly without the <code>Pipeline</code> class' instance. As you can see <a href="https://jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps" rel="nofollow noreferrer">here</a> they passing <code>this</code> to the method <code>mvn</code>.</p>
  
  <p>Thinking of avoid this I was wondering about dynamically add all methods as closures by calling <code>Utils.install this</code> instead of using <code>import static Utils.*</code>, then my <code>Utils.groovy</code> is something like that:</p>
  
  <pre><code>package com.company
  
  private Utils() {}
  
  static def install(def instance) {
    def utils = new Utils()
    // Some extra check needed here I know, but it is not the problem now
    for (def method in (utils.metaClass.methods*.name as Set) - (instance.metaClass.methods*.name as Set)) {
      def closure = utils.&amp;"$method"
      closure.delegate = instance
      instance.metaClass."$method" = closure
    }
  }
  
  def someMethod() {
    // here I want to use sh(), tool(), and other stuff freely.
  }
  </code></pre>
  
  <p>But it raises an <code>GStringImpl</code> cannot be cast to <code>String</code> error, I believe <code>.&amp;</code> do not work with variables, how can I convert a method into closure having the method name on a variable? I have the <a href="http://docs.groovy-lang.org/latest/html/api/groovy/lang/MetaMethod.html" rel="nofollow noreferrer"><code>MetaMethod</code></a> mostly being a <a href="http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/reflection/CachedMethod.html" rel="nofollow noreferrer"><code>CachedMethod</code></a> instance, if it were possible to turn it a <a href="http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.html" rel="nofollow noreferrer"><code>ClosureMetaMethod</code></a> instance maybe the problem can be solved, but whenever I search for method to closure conversion for groovy I just found the <code>.&amp;</code> solution!</p>
  
  <p>If I use <code>instance.metaClass.someMethod = utils.&amp;someMethod</code> it do work, but I want it to be dinamic as I add new methods without needing to worry about sharing it.</p>