Dynamic Proxy
70 likes | 90 Vues
Dynamic Proxy. Proxy: Addition to the Java 1.3 reflection package: implements a list of interfaces specified at runtime can be used as if the Proxy class implemented these interfaces! when invoked passes the “method invocation” to an implementation of the InvocationHandler
Dynamic Proxy
E N D
Presentation Transcript
Dynamic Proxy • Proxy: Addition to the Java 1.3 reflection package: • implements a list of interfaces specified at runtime • can be used as if the Proxy class implemented these interfaces! • when invoked passes the “method invocation” to an implementation of the InvocationHandler • how does this affect the stub-skeleton design? Good Java Programming
Dynamic Proxy: Instantiation InvocationHandler handler = new GenericSerializationHandler(); Foo1 proxyInstance = (Foo1) Proxy.newProxyInstance( Foo.class.getClassLoader(), new class[ ] { Foo.class, Foo1.class}, handler); Good Java Programming
Dynamic Proxy: Invocation // invocation examples ((Foo)proxyInstance).bar(); ((Foo1)proxyInstance).bar1(); Good Java Programming
Dynamic Proxy: Invocation Handler public GenericSerializationHandler implements InvocationHandler { … public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { String methodName = m.getName(); Class className = m.getDeclaringClass(); if (className.equals(Foo.class) && methodName.equals(“bar”)) { System.out.print(“Method bar called”); } } // className: interface on which the method was invoked // proxy: proxy instance on which the method was invoked // args: value of arguments in the methods Good Java Programming
Proxy Pattern • Provides a surrogate or placeholder for another object to control access to it. Good Java Programming
Proxy Pattern: Variations • Remote Proxy: controls access to a remote object • proxy acts as a local representative for an object in a different JVM • Virtual Proxy: controls access to a resource that is expensive to create • Defers creation of the object until needed • Once the object is created, proxy delegates requests to the real object • Caching Proxy • maintains a cache of previously created objects and returns cached objects whenever appropriate • Protection Proxy: controls access to a resource based on access rights • How can this be implemented using Dynamic Proxy in Java? Good Java Programming
Virtual Proxy • Defers creation of the object until needed • Once the object is created, proxy delegates requests to the real object • Example: • Creates a generic icon for an image, while waiting for the image to be retrieved from the network • Once the image is received, replaces the generic one with the actual image Good Java Programming