Alpha: Lightweight Dynamic Proxy API

I have added an alpha version of a dynamic proxy API to fluent reflection.

It allows you to define Java dynamic proxies using a light-weight fluent syntax. It uses the same reusable hamcrest matchers that are used throughout the rest of the fluent reflection API.

Overview

For example, to proxy a simple interface like this

interface TwoQueryMethod {
   int methodA();
 
   int methodB();
}

You define a new class which extends com.lexicalscope.fluentreflection.dynamicproxy.Implementing. You can define as many methods as you like inside this class. Each method should start by asserting what it is proxying by declaring a hamcrest matcher to match against the method currently being proxied. The first matching method found will be executed.

In this simple example each method is matched by exact name, but the matchers can be as complex as you need them to be:

final TwoQueryMethod dynamicProxy = dynamicProxy(new Implementing<TwoQueryMethod>() {
   public void bodyA() {
      whenProxying(callableHasName("methodA"));
      returnValue(42);
   }
 
   public void bodyB() {
      whenProxying(callableHasName("methodB"));
      returnValue(24);
   }
});

Method Arguments

The arguments of the original method are available from the context provided by the Implementing base class

interface MethodWithArgument {
   int method(int argument);
   String method(String argument);
}
 
final MethodWithArgument dynamicProxy = dynamicProxy(new Implementing<MethodWithArgument>() {
   public void body() {
      returnValue(args()[0]);
   }
});

An alternative approach can be used if you know in advance what the arguments of the method will be. In this example a matcher which matches against the arguments of each body is implied. The body will only be called if the proxied method call has arguments that can be used to satisfy the requirements of the body:

final MethodWithArgument dynamicProxy = dynamicProxy(new Implementing<MethodWithArgument>() {
   public int body(final int agument)
   {
      return 42;
   }
 
   public String body(final String agument)
   {
      return "42";
   }
});