Understanding Java Dynamic Proxies

OSOCO
OSOCOOSOCO
Understanding Dynamic Proxies
How to create proxy classes in runtime




Osoco
Rafael Luque
Introduction


Contents



1   Introduction


2   Creating a Proxy Class
      Proxy Class Properties


3   Creating a Proxy Instance


4   Examples




    Rafael Luque (Osoco)       Java Dynamic Proxies   04/2009   2 / 17
Introduction


Introduction



Dynamic Proxy Class
A class that implements a list of interfaces specified at runtime, such
that a method invocation through one of the interfaces on an instance
of the class will be encoded and dispatched to another object through
a uniform interface.

Usage
Create a proxy object for a list of interfaces without writing the proxy
class at compile-time.




    Rafael Luque (Osoco)        Java Dynamic Proxies             04/2009   3 / 17
Introduction


Introduction



Dynamic Proxy Class
A class that implements a list of interfaces specified at runtime, such
that a method invocation through one of the interfaces on an instance
of the class will be encoded and dispatched to another object through
a uniform interface.

Usage
Create a proxy object for a list of interfaces without writing the proxy
class at compile-time.




    Rafael Luque (Osoco)        Java Dynamic Proxies             04/2009   3 / 17
Creating a Proxy Class


Contents



1   Introduction


2   Creating a Proxy Class
      Proxy Class Properties


3   Creating a Proxy Instance


4   Examples




    Rafael Luque (Osoco)                Java Dynamic Proxies   04/2009   4 / 17
Creating a Proxy Class


Creating a Proxy Class

 • Proxy classes and instances are created using static methods of
   java.lang.reflect.Proxy.
 • Proxy.getProxyClass() returns the java.lang.Class
   object for a proxy class given a class loader and an array of
   interfaces.
 • The proxy class will be defined in the specified class loader and
   will implement all the interfaces.
 • Dynamic Proxy Class API implementations keep a cache of
   generated proxy classes:
       • If a proxy class for the same permutation of interfaces has already
           been defined by the class loader, then the existing proxy class will
           be returned; otherwise, a proxy class for those interfaces will be
           generated dynamically.


   Rafael Luque (Osoco)                Java Dynamic Proxies          04/2009   5 / 17
Creating a Proxy Class


Creating a Proxy Class

 • Proxy classes and instances are created using static methods of
   java.lang.reflect.Proxy.
 • Proxy.getProxyClass() returns the java.lang.Class
   object for a proxy class given a class loader and an array of
   interfaces.
 • The proxy class will be defined in the specified class loader and
   will implement all the interfaces.
 • Dynamic Proxy Class API implementations keep a cache of
   generated proxy classes:
       • If a proxy class for the same permutation of interfaces has already
           been defined by the class loader, then the existing proxy class will
           be returned; otherwise, a proxy class for those interfaces will be
           generated dynamically.


   Rafael Luque (Osoco)                Java Dynamic Proxies          04/2009   5 / 17
Creating a Proxy Class


Creating a Proxy Class

 • Proxy classes and instances are created using static methods of
   java.lang.reflect.Proxy.
 • Proxy.getProxyClass() returns the java.lang.Class
   object for a proxy class given a class loader and an array of
   interfaces.
 • The proxy class will be defined in the specified class loader and
   will implement all the interfaces.
 • Dynamic Proxy Class API implementations keep a cache of
   generated proxy classes:
       • If a proxy class for the same permutation of interfaces has already
           been defined by the class loader, then the existing proxy class will
           be returned; otherwise, a proxy class for those interfaces will be
           generated dynamically.


   Rafael Luque (Osoco)                Java Dynamic Proxies          04/2009   5 / 17
Creating a Proxy Class


Creating a Proxy Class

 • Proxy classes and instances are created using static methods of
   java.lang.reflect.Proxy.
 • Proxy.getProxyClass() returns the java.lang.Class
   object for a proxy class given a class loader and an array of
   interfaces.
 • The proxy class will be defined in the specified class loader and
   will implement all the interfaces.
 • Dynamic Proxy Class API implementations keep a cache of
   generated proxy classes:
       • If a proxy class for the same permutation of interfaces has already
           been defined by the class loader, then the existing proxy class will
           be returned; otherwise, a proxy class for those interfaces will be
           generated dynamically.


   Rafael Luque (Osoco)                Java Dynamic Proxies          04/2009   5 / 17
Creating a Proxy Class


Creating a Proxy Class

 • Proxy classes and instances are created using static methods of
   java.lang.reflect.Proxy.
 • Proxy.getProxyClass() returns the java.lang.Class
   object for a proxy class given a class loader and an array of
   interfaces.
 • The proxy class will be defined in the specified class loader and
   will implement all the interfaces.
 • Dynamic Proxy Class API implementations keep a cache of
   generated proxy classes:
       • If a proxy class for the same permutation of interfaces has already
           been defined by the class loader, then the existing proxy class will
           be returned; otherwise, a proxy class for those interfaces will be
           generated dynamically.


   Rafael Luque (Osoco)                Java Dynamic Proxies          04/2009   5 / 17
Creating a Proxy Class


Proxy.getProxyClass Method




Proxy.getProxyClass() method
  public static Class getProxyClass(
             ClassLoader loader,
             Class[] interfaces)
        throws IllegalArgumentException




   Rafael Luque (Osoco)                Java Dynamic Proxies   04/2009   6 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Class   Proxy Class Properties


Proxy Class Properties


 • Proxy classes are public, final, and not abstract.
 • A proxy class extends java.lang.reflect.Proxy.
 • The unqualified name of a proxy class is unspecified.
 • If a proxy class implements a non-public interface, then it will be
   defined in the same package as that interface. Otherwise, the
   package of a proxy class is also unspecified.
 • A proxy class implements exactly the interfaces specified at its
   creation, in the same order.
 • The Proxy.isProxyClass will return true if it is passed a proxy
   class.



   Rafael Luque (Osoco)                Java Dynamic Proxies                 04/2009   7 / 17
Creating a Proxy Instance


Contents



1   Introduction


2   Creating a Proxy Class
      Proxy Class Properties


3   Creating a Proxy Instance


4   Examples




    Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   8 / 17
Creating a Proxy Instance


Invocation Handler



 • Each proxy instance has an associated invocation handler object,
   which implements the interface
   java.lang.reflect.InvocationHandler.
 • A method invocation on a proxy instance will be dispatched to the
   invoke method of the instance’s invocation handler.
 • Invoke method receives the proxy instance, a
   java.lang.reflect.Method object identifying the method
   that was invoked and an array of type Object containing the
   arguments.




   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   9 / 17
Creating a Proxy Instance


Invocation Handler



 • Each proxy instance has an associated invocation handler object,
   which implements the interface
   java.lang.reflect.InvocationHandler.
 • A method invocation on a proxy instance will be dispatched to the
   invoke method of the instance’s invocation handler.
 • Invoke method receives the proxy instance, a
   java.lang.reflect.Method object identifying the method
   that was invoked and an array of type Object containing the
   arguments.




   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   9 / 17
Creating a Proxy Instance


Invocation Handler



 • Each proxy instance has an associated invocation handler object,
   which implements the interface
   java.lang.reflect.InvocationHandler.
 • A method invocation on a proxy instance will be dispatched to the
   invoke method of the instance’s invocation handler.
 • Invoke method receives the proxy instance, a
   java.lang.reflect.Method object identifying the method
   that was invoked and an array of type Object containing the
   arguments.




   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   9 / 17
Creating a Proxy Instance


Proxy Instance I


  • Each proxy class has one public constructor that takes as
    argument an implementation of the interface
    InvocationHandler.
  • You can instantiate the proxy class using the reflection API:

Proxy for the Foo interface
  Class proxyClass = Proxy.getProxyClass(
      Foo.class.getClassLoader(), new Class[] { Foo.class });
  InvocationHandler handler = new MyInvocationHandler(...);
  Foo f = (Foo) proxyClass.
      getConstructor(new Class[] { InvocationHandler.class }).
      newInstance(new Object[] { handler });




    Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   10 / 17
Creating a Proxy Instance


Proxy Instance II


  • Better, you can use the Proxy.newProxyInstance method:

Proxy using Proxy.newProxyInstance
  InvocationHandler handler = new MyInvocationHandler(...);
  Foo f = (Foo) Proxy.newProxyInstance(
      Foo.class.getClassLoader(),
      new Class[] { Foo.class },
      handler);


  • This method combines the actions of calling
    Proxy.getProxyClass with invoking the constructor with an
    invocation handler.




   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   11 / 17
Creating a Proxy Instance


Proxy Instance Properties I


  • Given a proxy instance proxy and one of the interfaces
    implemented by its proxy class Foo, the following expression will
    return true:
            proxy instanceof Foo

    and the following cast operation will succeed:
            (Foo) proxy

  • The static Proxy.getInvocationHandler method will return
    the invocation handler associated with the proxy instance passed
    as its argument.


   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   12 / 17
Creating a Proxy Instance


Proxy Instance Properties II



  • An interface method invocation on a proxy instance will be
    encoded and dispatched to the invocation handler’s invoke
    method.
  • An invocation of the hashCode, equals, or toString methods
    declared in java.lang.Object on a proxy instance will be also
    encoded and dispatched.




   Rafael Luque (Osoco)                   Java Dynamic Proxies   04/2009   13 / 17
Examples


Contents



1   Introduction


2   Creating a Proxy Class
      Proxy Class Properties


3   Creating a Proxy Instance


4   Examples




    Rafael Luque (Osoco)       Java Dynamic Proxies   04/2009   14 / 17
Examples


 DebugProxy Example I
     A proxy that prints out a message before and after each method
     invocation on an object that implements an arbitrary list of interfaces.
1        import j a v a . l a n g . r e f l e c t . Proxy ;
2
3        public class DebugProxy
4            implements j a v a . l a n g . r e f l e c t . I n v o c a t i o n H a n d l e r {
5
6           private Object obj ;
7
8           public s t a t i c O b j e c t newInstance ( O b j e c t o b j ) {
9             r e t u r n Proxy . newProxyInstance (
10                o b j . g e t C l a s s ( ) . getClassLoader ( ) ,
11                obj . getClass ( ) . g e t I n t e r f a c e s ( ) ,
12               new DebugProxy ( o b j ) ) ;
13          }
14
15          p r i v a t e DebugProxy ( O b j e c t o b j ) {
16              this . obj = obj ;
17          }
18


         Rafael Luque (Osoco)                      Java Dynamic Proxies                           04/2009   15 / 17
Examples


 DebugProxy Example II

19       public O b j e c t i n v o k e ( O b j e c t proxy , Method m, O b j e c t [ ] args )
20           throws Throwable {
21
22           Object r e s u l t ;
23           try {
24             System . o u t . p r i n t l n ( ‘ ‘ b e f o r e method ’ ’ ) ;
25             r e s u l t = m. i n v o k e ( obj , args ) ;
26           } catch ( I n v o c a t i o n T a r g e t E x c e p t i o n e ) {
27             throw e . g e t T a r g e t E x c e p t i o n ( ) ;
28           } catch ( E x c e p t i o n e ) {
29             throw new RuntimeException ( ) ;
30           } finally {
31             System . o u t . p r i n t l n ( ‘ ‘ a f t e r method ’ ’ ) ;
32           }
33           return r e s u l t ;
34
35       }
36
37   }



     Rafael Luque (Osoco)                       Java Dynamic Proxies                    04/2009   16 / 17
Understanding Dynamic Proxies
How to create proxy classes in runtime




Osoco
Rafael Luque
1 of 29

Recommended

Dynamic Proxy by Java by
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by JavaKan-Han (John) Lu
761 views14 slides
55 new things in Java 7 - Devoxx France by
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
1.9K views73 slides
Java byte code & virtual machine by
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machineLaxman Puri
3.7K views27 slides
Java bytecode and classes by
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
3.3K views42 slides
JAVA BYTE CODE by
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODEJaved Ahmed Samo
1.2K views20 slides
Understanding Java Dynamic Proxies by
Understanding Java Dynamic ProxiesUnderstanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesRafael Luque Leiva
1.2K views29 slides

More Related Content

What's hot

Understanding ClassLoaders by
Understanding ClassLoadersUnderstanding ClassLoaders
Understanding ClassLoadersMartin Skurla
344 views33 slides
Java class loader by
Java class loaderJava class loader
Java class loaderbenewu
1.9K views41 slides
What is-java by
What is-javaWhat is-java
What is-javaShahid Rasheed
600 views19 slides
Let's talk about java class loader by
Let's talk about java class loaderLet's talk about java class loader
Let's talk about java class loaderYongqiang Li
1.4K views16 slides
Java Class Loading by
Java Class LoadingJava Class Loading
Java Class LoadingSandeep Verma
4.2K views7 slides
Java Classloaders by
Java ClassloadersJava Classloaders
Java ClassloadersPrateek Jain
1.3K views20 slides

What's hot(20)

Understanding ClassLoaders by Martin Skurla
Understanding ClassLoadersUnderstanding ClassLoaders
Understanding ClassLoaders
Martin Skurla344 views
Java class loader by benewu
Java class loaderJava class loader
Java class loader
benewu1.9K views
Let's talk about java class loader by Yongqiang Li
Let's talk about java class loaderLet's talk about java class loader
Let's talk about java class loader
Yongqiang Li1.4K views
Java Classloaders by Prateek Jain
Java ClassloadersJava Classloaders
Java Classloaders
Prateek Jain1.3K views
Java class loading tips and tricks - Java Colombo Meetup, January, 2014 by Sameera Jayasoma
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
Sameera Jayasoma6.1K views
Great cup of java by CIB Egypt
Great  cup of javaGreat  cup of java
Great cup of java
CIB Egypt999 views
Java Interview Questions Answers Guide by DaisyWatson5
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
DaisyWatson5296 views
An Introduction to Java Compiler and Runtime by Omar Bashir
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir1.9K views
First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie... by ESUG
First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie...First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie...
First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie...
ESUG416 views
Java compilation by Mike Kucera
Java compilationJava compilation
Java compilation
Mike Kucera956 views

Viewers also liked

AWS CloudFormation en 5 Minutos by
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosOSOCO
3.2K views17 slides
SSH Tunneling Recipes by
SSH Tunneling RecipesSSH Tunneling Recipes
SSH Tunneling RecipesOSOCO
6.8K views56 slides
Spring Annotations: Proxy by
Spring Annotations: ProxySpring Annotations: Proxy
Spring Annotations: ProxyOSOCO
1.5K views12 slides
Polyglot Grails by
Polyglot GrailsPolyglot Grails
Polyglot GrailsMarcin Gryszko
3.5K views71 slides
Proactive monitoring with Monit by
Proactive monitoring with MonitProactive monitoring with Monit
Proactive monitoring with MonitOSOCO
2.9K views38 slides
Polyglot JVM by
Polyglot JVMPolyglot JVM
Polyglot JVMArturo Herrero
10.4K views70 slides

Viewers also liked(18)

AWS CloudFormation en 5 Minutos by OSOCO
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 Minutos
OSOCO3.2K views
SSH Tunneling Recipes by OSOCO
SSH Tunneling RecipesSSH Tunneling Recipes
SSH Tunneling Recipes
OSOCO6.8K views
Spring Annotations: Proxy by OSOCO
Spring Annotations: ProxySpring Annotations: Proxy
Spring Annotations: Proxy
OSOCO1.5K views
Proactive monitoring with Monit by OSOCO
Proactive monitoring with MonitProactive monitoring with Monit
Proactive monitoring with Monit
OSOCO2.9K views
Object relationship mapping and hibernate by Joe Jacob
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernate
Joe Jacob1.9K views
Proxy deep-dive java-one_20151027_001 by Sven Ruppert
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001
Sven Ruppert2.7K views
Classloading and Type Visibility in OSGi by martinlippert
Classloading and Type Visibility in OSGiClassloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGi
martinlippert6.9K views
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017) by Alex Rupérez
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
Alex Rupérez19.9K views
Gigigo Keynote - Geofences & iBeacons by Alex Rupérez
Gigigo Keynote - Geofences & iBeaconsGigigo Keynote - Geofences & iBeacons
Gigigo Keynote - Geofences & iBeacons
Alex Rupérez127.3K views
NSCoder Keynote - Multipeer Connectivity Framework by Alex Rupérez
NSCoder Keynote - Multipeer Connectivity FrameworkNSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity Framework
Alex Rupérez78.2K views
Gigigo Workshop - Create an iOS Framework, document it and not die trying by Alex Rupérez
Gigigo Workshop - Create an iOS Framework, document it and not die tryingGigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die trying
Alex Rupérez42.2K views
Gigigo Workshop - iOS Extensions by Alex Rupérez
Gigigo Workshop - iOS ExtensionsGigigo Workshop - iOS Extensions
Gigigo Workshop - iOS Extensions
Alex Rupérez33.6K views
Hibernate Presentation by guest11106b
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b20.4K views

Similar to Understanding Java Dynamic Proxies

Java architecture for xml binding by
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml bindingKiran Gajbhiye
101 views8 slides
5 the final_hard_part by
5 the final_hard_part5 the final_hard_part
5 the final_hard_partHonnix Liang
304 views58 slides
A begineers guide of JAVA - Getting Started by
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
797 views25 slides
A Guide to Java Dynamic Proxies and It in Coding by
A Guide to Java Dynamic Proxies and It in CodingA Guide to Java Dynamic Proxies and It in Coding
A Guide to Java Dynamic Proxies and It in CodingMikeConner22
8 views4 slides
chap 10 : Development (scjp/ocjp) by
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)It Academy
497 views16 slides
Java programming notes by
Java programming notesJava programming notes
Java programming notesKetan Rajpal
1.3K views27 slides

Similar to Understanding Java Dynamic Proxies(20)

Java architecture for xml binding by Kiran Gajbhiye
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
Kiran Gajbhiye101 views
5 the final_hard_part by Honnix Liang
5 the final_hard_part5 the final_hard_part
5 the final_hard_part
Honnix Liang304 views
A begineers guide of JAVA - Getting Started by Rakesh Madugula
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
Rakesh Madugula797 views
A Guide to Java Dynamic Proxies and It in Coding by MikeConner22
A Guide to Java Dynamic Proxies and It in CodingA Guide to Java Dynamic Proxies and It in Coding
A Guide to Java Dynamic Proxies and It in Coding
MikeConner228 views
chap 10 : Development (scjp/ocjp) by It Academy
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
It Academy497 views
Java programming notes by Ketan Rajpal
Java programming notesJava programming notes
Java programming notes
Ketan Rajpal1.3K views
JVM, JRE and Javac are the main part for the java program by siyaram ray
 JVM, JRE and Javac are the main part for the java program JVM, JRE and Javac are the main part for the java program
JVM, JRE and Javac are the main part for the java program
siyaram ray223 views
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo by Jeffrey West
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool DemoWebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
Jeffrey West3.3K views
WebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis Tool by Jeffrey West
WebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis ToolWebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis Tool
WebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis Tool
Jeffrey West9K views
OOP with Java by OmegaHub
OOP with JavaOOP with Java
OOP with Java
OmegaHub30 views
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз... by QAFest
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QAFest1.4K views

Recently uploaded

CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TShapeBlue
81 views34 slides
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsShapeBlue
172 views13 slides
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...Bernd Ruecker
50 views69 slides
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...ShapeBlue
105 views15 slides
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
49 views35 slides
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue by
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlueShapeBlue
75 views23 slides

Recently uploaded(20)

CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue81 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue172 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker50 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue105 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue by ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
ShapeBlue75 views
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by ShapeBlue
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
ShapeBlue59 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson142 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue154 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue110 views
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue86 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue74 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue48 views
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... by ShapeBlue
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
ShapeBlue52 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue149 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue178 views
Digital Personal Data Protection (DPDP) Practical Approach For CISOs by Priyanka Aash
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOs
Priyanka Aash103 views
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue97 views

Understanding Java Dynamic Proxies

  • 1. Understanding Dynamic Proxies How to create proxy classes in runtime Osoco Rafael Luque
  • 2. Introduction Contents 1 Introduction 2 Creating a Proxy Class Proxy Class Properties 3 Creating a Proxy Instance 4 Examples Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 2 / 17
  • 3. Introduction Introduction Dynamic Proxy Class A class that implements a list of interfaces specified at runtime, such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Usage Create a proxy object for a list of interfaces without writing the proxy class at compile-time. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 3 / 17
  • 4. Introduction Introduction Dynamic Proxy Class A class that implements a list of interfaces specified at runtime, such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Usage Create a proxy object for a list of interfaces without writing the proxy class at compile-time. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 3 / 17
  • 5. Creating a Proxy Class Contents 1 Introduction 2 Creating a Proxy Class Proxy Class Properties 3 Creating a Proxy Instance 4 Examples Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 4 / 17
  • 6. Creating a Proxy Class Creating a Proxy Class • Proxy classes and instances are created using static methods of java.lang.reflect.Proxy. • Proxy.getProxyClass() returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. • The proxy class will be defined in the specified class loader and will implement all the interfaces. • Dynamic Proxy Class API implementations keep a cache of generated proxy classes: • If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 5 / 17
  • 7. Creating a Proxy Class Creating a Proxy Class • Proxy classes and instances are created using static methods of java.lang.reflect.Proxy. • Proxy.getProxyClass() returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. • The proxy class will be defined in the specified class loader and will implement all the interfaces. • Dynamic Proxy Class API implementations keep a cache of generated proxy classes: • If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 5 / 17
  • 8. Creating a Proxy Class Creating a Proxy Class • Proxy classes and instances are created using static methods of java.lang.reflect.Proxy. • Proxy.getProxyClass() returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. • The proxy class will be defined in the specified class loader and will implement all the interfaces. • Dynamic Proxy Class API implementations keep a cache of generated proxy classes: • If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 5 / 17
  • 9. Creating a Proxy Class Creating a Proxy Class • Proxy classes and instances are created using static methods of java.lang.reflect.Proxy. • Proxy.getProxyClass() returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. • The proxy class will be defined in the specified class loader and will implement all the interfaces. • Dynamic Proxy Class API implementations keep a cache of generated proxy classes: • If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 5 / 17
  • 10. Creating a Proxy Class Creating a Proxy Class • Proxy classes and instances are created using static methods of java.lang.reflect.Proxy. • Proxy.getProxyClass() returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. • The proxy class will be defined in the specified class loader and will implement all the interfaces. • Dynamic Proxy Class API implementations keep a cache of generated proxy classes: • If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 5 / 17
  • 11. Creating a Proxy Class Proxy.getProxyClass Method Proxy.getProxyClass() method public static Class getProxyClass( ClassLoader loader, Class[] interfaces) throws IllegalArgumentException Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 6 / 17
  • 12. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 13. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 14. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 15. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 16. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 17. Creating a Proxy Class Proxy Class Properties Proxy Class Properties • Proxy classes are public, final, and not abstract. • A proxy class extends java.lang.reflect.Proxy. • The unqualified name of a proxy class is unspecified. • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. • A proxy class implements exactly the interfaces specified at its creation, in the same order. • The Proxy.isProxyClass will return true if it is passed a proxy class. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 7 / 17
  • 18. Creating a Proxy Instance Contents 1 Introduction 2 Creating a Proxy Class Proxy Class Properties 3 Creating a Proxy Instance 4 Examples Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 8 / 17
  • 19. Creating a Proxy Instance Invocation Handler • Each proxy instance has an associated invocation handler object, which implements the interface java.lang.reflect.InvocationHandler. • A method invocation on a proxy instance will be dispatched to the invoke method of the instance’s invocation handler. • Invoke method receives the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 9 / 17
  • 20. Creating a Proxy Instance Invocation Handler • Each proxy instance has an associated invocation handler object, which implements the interface java.lang.reflect.InvocationHandler. • A method invocation on a proxy instance will be dispatched to the invoke method of the instance’s invocation handler. • Invoke method receives the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 9 / 17
  • 21. Creating a Proxy Instance Invocation Handler • Each proxy instance has an associated invocation handler object, which implements the interface java.lang.reflect.InvocationHandler. • A method invocation on a proxy instance will be dispatched to the invoke method of the instance’s invocation handler. • Invoke method receives the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 9 / 17
  • 22. Creating a Proxy Instance Proxy Instance I • Each proxy class has one public constructor that takes as argument an implementation of the interface InvocationHandler. • You can instantiate the proxy class using the reflection API: Proxy for the Foo interface Class proxyClass = Proxy.getProxyClass( Foo.class.getClassLoader(), new Class[] { Foo.class }); InvocationHandler handler = new MyInvocationHandler(...); Foo f = (Foo) proxyClass. getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler }); Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 10 / 17
  • 23. Creating a Proxy Instance Proxy Instance II • Better, you can use the Proxy.newProxyInstance method: Proxy using Proxy.newProxyInstance InvocationHandler handler = new MyInvocationHandler(...); Foo f = (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader(), new Class[] { Foo.class }, handler); • This method combines the actions of calling Proxy.getProxyClass with invoking the constructor with an invocation handler. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 11 / 17
  • 24. Creating a Proxy Instance Proxy Instance Properties I • Given a proxy instance proxy and one of the interfaces implemented by its proxy class Foo, the following expression will return true: proxy instanceof Foo and the following cast operation will succeed: (Foo) proxy • The static Proxy.getInvocationHandler method will return the invocation handler associated with the proxy instance passed as its argument. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 12 / 17
  • 25. Creating a Proxy Instance Proxy Instance Properties II • An interface method invocation on a proxy instance will be encoded and dispatched to the invocation handler’s invoke method. • An invocation of the hashCode, equals, or toString methods declared in java.lang.Object on a proxy instance will be also encoded and dispatched. Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 13 / 17
  • 26. Examples Contents 1 Introduction 2 Creating a Proxy Class Proxy Class Properties 3 Creating a Proxy Instance 4 Examples Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 14 / 17
  • 27. Examples DebugProxy Example I A proxy that prints out a message before and after each method invocation on an object that implements an arbitrary list of interfaces. 1 import j a v a . l a n g . r e f l e c t . Proxy ; 2 3 public class DebugProxy 4 implements j a v a . l a n g . r e f l e c t . I n v o c a t i o n H a n d l e r { 5 6 private Object obj ; 7 8 public s t a t i c O b j e c t newInstance ( O b j e c t o b j ) { 9 r e t u r n Proxy . newProxyInstance ( 10 o b j . g e t C l a s s ( ) . getClassLoader ( ) , 11 obj . getClass ( ) . g e t I n t e r f a c e s ( ) , 12 new DebugProxy ( o b j ) ) ; 13 } 14 15 p r i v a t e DebugProxy ( O b j e c t o b j ) { 16 this . obj = obj ; 17 } 18 Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 15 / 17
  • 28. Examples DebugProxy Example II 19 public O b j e c t i n v o k e ( O b j e c t proxy , Method m, O b j e c t [ ] args ) 20 throws Throwable { 21 22 Object r e s u l t ; 23 try { 24 System . o u t . p r i n t l n ( ‘ ‘ b e f o r e method ’ ’ ) ; 25 r e s u l t = m. i n v o k e ( obj , args ) ; 26 } catch ( I n v o c a t i o n T a r g e t E x c e p t i o n e ) { 27 throw e . g e t T a r g e t E x c e p t i o n ( ) ; 28 } catch ( E x c e p t i o n e ) { 29 throw new RuntimeException ( ) ; 30 } finally { 31 System . o u t . p r i n t l n ( ‘ ‘ a f t e r method ’ ’ ) ; 32 } 33 return r e s u l t ; 34 35 } 36 37 } Rafael Luque (Osoco) Java Dynamic Proxies 04/2009 16 / 17
  • 29. Understanding Dynamic Proxies How to create proxy classes in runtime Osoco Rafael Luque