How do I get the underlying type of a proxy object in java?

Viewed 34222

I'd like to access the classname of the underlying class which is an instance of java.lang.reflect.Proxy.

Is this possible?

9 Answers

Simple and robust:

AopUtils.getTargetClass(object).getName(); 

Will also work for CGLIB proxies and non-proxy objects.

I found the perfect solution for me in org.springframework.aop.framework.AopProxyUtils:

AopProxyUtils.ultimateTargetClass(object).getCanonicalName()

Static Hibernate.getClass() might be useful in this scenario.

Get the true, underlying class of a proxied persistent class

    public static Class getClass(Object proxy) {
        if ( proxy instanceof HibernateProxy ) {
            return ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer()
                    .getImplementation()
                    .getClass();
        }
        else {
            return proxy.getClass();
        }
    }
Related