Tuesday, 5 May 2020

Javassist: check whether object is proxy?

‘ProxyFactory.isProxyClass’ method return true if the given class is proxy class else false. 

 

Example

GreetUser greetUser1 = ….;

 

boolean isProxyClass = ProxyFactory.isProxyClass(greetUser1.getClass());

 

if (isProxyClass) {

    System.out.println("Given class is proxy class");

} else {

    System.out.println("Given class is not proxy class");

}

 

 

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 greetUser1 = createProxy(GreetUser.class);

        boolean isProxyClass = ProxyFactory.isProxyClass(greetUser1.getClass());

        if (isProxyClass) {
            System.out.println("Given class is proxy class");
        } else {
            System.out.println("Given class is not proxy class");
        }

        GreetUser greetUser2 = new GreetUser();
        isProxyClass = ProxyFactory.isProxyClass(greetUser2.getClass());

        if (isProxyClass) {
            System.out.println("Given class is proxy class");
        } else {
            System.out.println("Given class is not proxy class");
        }

    }
}

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

 

Given class is proxy class

Given class is not proxy class





Previous                                                    Next                                                    Home

No comments:

Post a Comment