ProxyToys is not difficult. If you are familiar with the Proxy class of the JDK, then you already know how to use a ProxyFactory.
Create a ProxyFactory and use it to create a proxy
See this simple example, that creates a ProxyFactory based on the JDK. We just hide the ArrayList instance behind the List interface:
ProxyFactory factory = new StandardProxyFactory(); List proxy = (List)factory.createProxy(new Class[]{List.class}, new SimpleInvoker(new ArrayList())); 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 accessable.
Just replace the instance of the StandardProxyFactory with CglibProxyFactory to use a different implementation. You have to put the cglib-nodep-2.1.jar into your classpath though.
Using the toys
Each toy is a factory for proxy instances, that solve a common usage pattern of a proxy instance. Every toys (except the Pool), has a factory with a static interface:
<Toy>.object(...);
As example see a usage of the Echo toy:
Map map = (Map)Echoing.object(Map.class, new HashMap()); map.put("hello", "world");
This proxy is generated by a StandardproxyFactory, implements the Map interface and any call done to the
underlaying object will be printed to System.out
.
Look at the different package descriptions of each toy. Everyone contains a description for the usage and examples.