Showing posts with label java proxy object. Show all posts
Showing posts with label java proxy object. Show all posts

How to create Proxy object in java | creation of proxy object concept in spring AOP

J2SE v1.3 has introduced a dynamic proxy class in the Java Reflection package.
A dynamic proxy class 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.
 Proxy classes and instances are created using static methods of the java.lang.reflect.Proxy class.Each proxy class has one public constructor that takes one argument, an implementation of the java.lang.reflect.InvocationHandler interface.


package com.prox;

public interface Showable {
   
public void show();
}





-------------------------------------


package com.prox;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyHandler implements InvocationHandler{
   
    Showable target;
    public  MyHandler(Showable target)
    {
        this.target=target;
    }
    public Object invoke(Object proxy, Method m, Object [] args)throws Throwable
    {
        Object o= m.invoke(target, args);
        return o;
    }

}


------------------------------------------

package com.prox;

public class A implements Showable{
   
    public void show()
    {
       
        System.out.println("Inside the Class A");
    }

}


---------------------------------------------


package com.prox;


import java.lang.reflect.Proxy;

public class ProxyTest {
   
    public static void main(String [] args)
    {
       
        System.out.println("Inside the main method");
        A  target = new  A();
        B  target1 = new  B();
        MyHandler handler= new MyHandler(target1);
        try {
         System.out.println("creating Proxy object");
         Showable pr=(Showable)Proxy.newProxyInstance(B.class.getClassLoader(),new
                Class[]{Showable.class}, handler);
       
        System.out.println("The Invoking show method on proxy object");
        pr.show();
        System.out.println("the proxy object"+pr.getClass().getName());
        //B b=(B)pr;
        //b.notShow();
        }
       
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

}


-------------------------------------------

In above code we have created a proxy object concept

Drawback of proxy object

  • One limitation is that the method must be called through an instance of the proxy class. So nested methods calls, for instance, would not be intercepted.
  • Another limitation is that the method must have been defined in an Interface that is implemented by the object being proxied. It can not be called through an instance of a class that does not implement an interface.