title: How to create a dynamic proxy using ByteBuddy
body: <p>In Java it is possible to create dynamic proxies using an implementation of <code>InvocationHandler</code>. Despite JVM optimizations, using reflection will always have some overhead invoking a method.</p>
  
  <p>To try to solve this problem, I tried to use ByteBuddy to create the proxy classes at runtime, but the documentation didn't seem clear enough on this aspect.</p>
  
  <p>How do I create a <code>MethodCallProxy</code> in order to forward a method invocation to some class instance?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>To better clarify my problem, I am providing an example of what I want to achieve:</p>
  
  <p>I am building an RPC system. On each side of a method invocation, I have an interface defining the contract (when both caller/callee are running under the JVM).</p>
  
  <pre><code>@Contract
  interface ISomeService {
      fun someMethod(arg0: String, arg1: SomePojo): PojoResult
  }
  </code></pre>
  
  <p>At the call site, I inject a proxy that intercepts all method calls and forwards them to the callee.</p>
  
  <pre><code>ByteBuddy()
      .subclass(Any::class.java)
      .implement(serviceClass)
  
      // Service contract method delegation
      .method(isDeclaredBy(serviceClass)).intercept(
        MethodDelegation
            .to(ServiceProxyInterceptor())
            .filter(not(isDeclaredBy(Any::class.java)))
      )
  
      .make()
      .load(this)
      .loaded as Class&lt;T&gt;
  </code></pre>
  
  <p>And, finally, at the callee, I have several handlers, one for each service method, responsible for unmarshalling the invocation parameters and forwarding them to the service implementation.</p>
  
  <pre><code>@Service
  class SomeServiceImpl {
      fun someMethod(arg0: String, arg1: SomePojo): PojoResult {
          // ...
      }
  }
  </code></pre>
  
  <p>I could solve this problem using code generation, but the resulting <code>jar</code> file can become very big. Thus, I want to create a generic version of these handlers and, in each instance, attach a proxy that intercepts every method call to <code>ISomeService</code> and forwards them to <code>SomeServiceImpl</code>.</p>