The steps are shown in the following code:
InvocationHandler handler = new SomeInvocationHandler(...);
Class proxyClazz = Proxy.getProxyClass(Blah.class.getClassLoader(),
new Class[] {Blah.class});
Blah blah = (Blah) proxyClazz.getConstructor(new Class[] {
InvocationHandler.class }).newInstance(new Object[]
{handler});
There is also a shortcut to get a proxy object. You can invoke Proxy.
newProxyInstance, which takes a class loader, an array of interface classes, and an
invocation handler instance.
InvocationHandler handler = new SomeInvocationHandler(...);
Blah blah = (Blah) Proxy.newProxyInstance(Blah.class.
getClassLoader(),new Class[] {Blah.class},
handler);
Now you can invoke methods on the proxy object during which these method
invocations are turned into calls on to the invocation handler's invoke method is
shown here:
blah.interfaceMethod();
Sample JDK Proxy Class
We will now write some simple code to demonstrate how you can write your own
proxies at run time, for your interface classes.
As a first step, if you haven't done it before, edit examples.PROPERTIES (provided
along with the code download for this chapter), and change the paths there to match
your development environment.
Pages:
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334