SlideShare a Scribd company logo
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

More Related Content

What's hot

Understanding ClassLoaders
Understanding ClassLoadersUnderstanding ClassLoaders
Understanding ClassLoaders
Martin Skurla
 
Java class loader
Java class loaderJava class loader
Java class loader
benewu
 
What is-java
What is-javaWhat is-java
What is-java
Shahid Rasheed
 
Let's talk about java class loader
Let's talk about java class loaderLet's talk about java class loader
Let's talk about java class loader
Yongqiang Li
 
Java Class Loading
Java Class LoadingJava Class Loading
Java Class Loading
Sandeep Verma
 
Java Classloaders
Java ClassloadersJava Classloaders
Java Classloaders
Prateek Jain
 
Lecture 3
Lecture 3Lecture 3
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
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 Jayasoma
 
Java architecture
Java architectureJava architecture
Java architecture
Rakesh Vadnala
 
Great cup of java
Great  cup of javaGreat  cup of java
Great cup of java
CIB Egypt
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
DaisyWatson5
 
Java Virtual Machine
Java Virtual MachineJava Virtual Machine
Java Virtual Machine
Taha Malampatti
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
Nikhil Sharma
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
Ideal Eyes Business College
 
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...
First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie...
ESUG
 
History of java'
History of java'History of java'
History of java'
deepthisujithra
 
Class loaders
Class loadersClass loaders
Java
JavaJava
Java
Abrar ali
 
Java compilation
Java compilationJava compilation
Java compilation
Mike Kucera
 

What's hot (20)

Understanding ClassLoaders
Understanding ClassLoadersUnderstanding ClassLoaders
Understanding ClassLoaders
 
Java class loader
Java class loaderJava class loader
Java class loader
 
What is-java
What is-javaWhat is-java
What is-java
 
Let's talk about java class loader
Let's talk about java class loaderLet's talk about java class loader
Let's talk about java class loader
 
Java Class Loading
Java Class LoadingJava Class Loading
Java Class Loading
 
Java Classloaders
Java ClassloadersJava Classloaders
Java Classloaders
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
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
 
Java architecture
Java architectureJava architecture
Java architecture
 
Great cup of java
Great  cup of javaGreat  cup of java
Great cup of java
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
 
Java Virtual Machine
Java Virtual MachineJava Virtual Machine
Java Virtual Machine
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
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...
First-Class Undefined Classes for Pharo, From Alternative Designs to a Unifie...
 
History of java'
History of java'History of java'
History of java'
 
Class loaders
Class loadersClass loaders
Class loaders
 
Java
JavaJava
Java
 
Java compilation
Java compilationJava compilation
Java compilation
 

Viewers also liked

AWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 Minutos
OSOCO
 
SSH Tunneling Recipes
SSH Tunneling RecipesSSH Tunneling Recipes
SSH Tunneling Recipes
OSOCO
 
Spring Annotations: Proxy
Spring Annotations: ProxySpring Annotations: Proxy
Spring Annotations: Proxy
OSOCO
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
Marcin Gryszko
 
Proactive monitoring with Monit
Proactive monitoring with MonitProactive monitoring with Monit
Proactive monitoring with Monit
OSOCO
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
Arturo Herrero
 
Proxy & CGLIB
Proxy & CGLIBProxy & CGLIB
Proxy & CGLIB
beom kyun choi
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernate
Joe Jacob
 
Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001
Sven Ruppert
 
Classloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGiClassloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGi
martinlippert
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
Mohammad Faizan
 
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
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érez
 
Gigigo Keynote - Geofences & iBeacons
Gigigo Keynote - Geofences & iBeaconsGigigo Keynote - Geofences & iBeacons
Gigigo Keynote - Geofences & iBeacons
Alex Rupérez
 
NSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity FrameworkNSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity Framework
Alex Rupérez
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
Akshay Ballarpure
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
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érez
 
Gigigo Workshop - iOS Extensions
Gigigo Workshop - iOS ExtensionsGigigo Workshop - iOS Extensions
Gigigo Workshop - iOS Extensions
Alex Rupérez
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 

Viewers also liked (18)

AWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 Minutos
 
SSH Tunneling Recipes
SSH Tunneling RecipesSSH Tunneling Recipes
SSH Tunneling Recipes
 
Spring Annotations: Proxy
Spring Annotations: ProxySpring Annotations: Proxy
Spring Annotations: Proxy
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
 
Proactive monitoring with Monit
Proactive monitoring with MonitProactive monitoring with Monit
Proactive monitoring with Monit
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Proxy & CGLIB
Proxy & CGLIBProxy & CGLIB
Proxy & CGLIB
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernate
 
Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001
 
Classloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGiClassloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGi
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
MADBike – Destapando la seguridad de BiciMAD (T3chFest 2017)
 
Gigigo Keynote - Geofences & iBeacons
Gigigo Keynote - Geofences & iBeaconsGigigo Keynote - Geofences & iBeacons
Gigigo Keynote - Geofences & iBeacons
 
NSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity FrameworkNSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity Framework
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
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
 
Gigigo Workshop - iOS Extensions
Gigigo Workshop - iOS ExtensionsGigigo Workshop - iOS Extensions
Gigigo Workshop - iOS Extensions
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 

Similar to Understanding Java Dynamic Proxies

Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
Kiran Gajbhiye
 
5 the final_hard_part
5 the final_hard_part5 the final_hard_part
5 the final_hard_part
Honnix Liang
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
It Academy
 
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
JVM, JRE and Javac are the main part for the java program
siyaram ray
 
WebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis Tool
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 West
 
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool DemoWebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
Jeffrey West
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Unit8 security (2) java
Unit8 security (2) javaUnit8 security (2) java
Unit8 security (2) java
Sharafat Husen
 
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptxchapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
FiromsaDine
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
OmegaHub
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
Brockhaus Group
 
Diving into Java Class Loader
Diving into Java Class LoaderDiving into Java Class Loader
Diving into Java Class Loader
Md Imran Hasan Hira
 
Rmi
RmiRmi
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
Patrick Sheridan
 
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QAFest
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
ProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applicationsProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applications
Binary Studio
 
Bringing classical OOP into JavaScript
Bringing classical OOP into JavaScriptBringing classical OOP into JavaScript
Bringing classical OOP into JavaScript
Dmitry Sheiko
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
Pankaj kshirsagar
 

Similar to Understanding Java Dynamic Proxies (20)

Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
 
5 the final_hard_part
5 the final_hard_part5 the final_hard_part
5 the final_hard_part
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
 
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
JVM, JRE and Javac are the main part for the java program
 
WebLogic's ClassLoaders, Filtering ClassLoader and ClassLoader Analysis Tool
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
 
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool DemoWebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
WebLogic Filtering ClassLoader and ClassLoader Analysis Tool Demo
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Unit8 security (2) java
Unit8 security (2) javaUnit8 security (2) java
Unit8 security (2) java
 
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptxchapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
Diving into Java Class Loader
Diving into Java Class LoaderDiving into Java Class Loader
Diving into Java Class Loader
 
Rmi
RmiRmi
Rmi
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
QA Fes 2016. Александр Хотемской. Обзор ProtractorJS как фреймворка для брауз...
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
ProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applicationsProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applications
 
Bringing classical OOP into JavaScript
Bringing classical OOP into JavaScriptBringing classical OOP into JavaScript
Bringing classical OOP into JavaScript
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 

Recently uploaded

Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 

Recently uploaded (20)

Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 

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