Tuesday 5 May 2020

Javassist: Create proxy to a class

Using 'ProxyFactory' class we can create proxy for an existing class.

 

Follow below steps to create proxy. 

 

Step 1: Create proxy class by setting original class as super class.

ProxyFactory factory = new ProxyFactory();

factory.setSuperclass(originalClass);

Class proxyClass = factory.createClass();

 

Step 2: Define instance of MethodHandler.

MethodHandler handler = new MethodHandler() {

 

         @Override

         public Object invoke(Object self, Method overridden, Method forwarder, Object[] args) throws Throwable {

                  System.out.println("Intercepting the method : " + overridden.getName());

 

                  try {

                           return forwarder.invoke(self, args);

                  } finally {

                           System.out.println("Method '" + overridden.getName() + "' execution is finished");

                  }

 

         }

};

 

Step 3: Get instance from proxy class.

Object proxyInstance = proxyClass.newInstance();

 

Step 4: Set method handler to the proxy instance.

((ProxyObject) proxyInstance).setHandler(handler);

 

That’s it you are done, now you can use proxy object.

 

Find the below working application.

 

GreetUser.java
package com.sample.app;

public class GreetUser {

  public void goodMorning() {
    System.out.println("Hello User, Good Morning!!!!");
  }

}

App.java

package com.sample.app;

import java.lang.reflect.Method;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

public class App {

  public static <T> T createProxy(Class<T> originalClass) throws Exception {
    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(originalClass);
    Class proxyClass = factory.createClass();

    MethodHandler handler = new MethodHandler() {

      @Override
      public Object invoke(Object self, Method overridden, Method forwarder, Object[] args) throws Throwable {
        System.out.println("Intercepting the method : " + overridden.getName());

        try {
          return forwarder.invoke(self, args);
        } finally {
          System.out.println("Method '" + overridden.getName() + "' execution is finished");
        }

      }
    };
    
    Object proxyInstance = proxyClass.newInstance();
    ((ProxyObject) proxyInstance).setHandler(handler);
    return (T) proxyInstance;
  }

  public static void main(String args[]) throws Exception {

    GreetUser greetUser = createProxy(GreetUser.class);

    greetUser.goodMorning();

  }
}

Run App.java, you will see below messages in console.

 

Intercepting the method : goodMorning

Hello User, Good Morning!!!!

Method 'goodMorning' execution is finished






Previous                                                    Next                                                    Home

No comments:

Post a Comment