ProxyToys is not difficult. If you are familiar with Reflection's Proxy class of the JDK, then you already know how to use a ProxyFactory.

Simple delegating example

See this simple example, that uses a ProxyFactory based on the Java's Reflection capability called StandardProxyFactory. The ArrayList passed in implementation-hidden behind the List interface:

List proxy = Delegating.proxy(List.class).with(new ArrayList()).build(new StandardProxyFactory())
proxy.add("Hello World");
System.out.println("Size of list: " + proxy.size());
System.out.println("First element of list: " + proxy.get(0));

Note: You can only use the methods of the List interface, to access the instance, methods like java.lang.ArrayList.ensureCapacity(int) are not accessible. You cannot cast back to implementation.

Just replace the instance of the StandardProxyFactory with CglibProxyFactory to use a different implementation. You have to put the cglib-nodep-2.2.jar (or above) into your classpath though. Also note that StandardProxyFactory is also the default, meaning you can used build() without parameters.

Simple Echoing example

Each toy is a factory for proxy instances, that solve a common usage pattern of a proxy instance. Every toy has a factory with a builder style API:


As example see a usage of the Echo toy:

Map<String, String> map = Echoing.proxy(Map.class)
    .with(new HashMap<String, String>())
    .to(new PrintWriter(System.out))
map.put("hello", "world");

This proxy is generated by a StandardProxyFactory, implements the Map interface and any call done to the underlying object will be printed to System.out.

There are many different ProxyToy types. See Toys