How do I retrieve the proxied class from the proxy class?

While I really like the simplicity of the approach posted by Flavio, I can't use it in production code unless it's documented as supported. Also, if you call .getImplementation() on the LazyInitializer, it will force the initialization of the proxy if it isn't already, which is a negative performance impact. I've come up with this approach which addresses both of these concerns:

public static Class<?> getClassForHibernateObject(Object object) {
  if (object instanceof HibernateProxy) {
    LazyInitializer lazyInitializer =
        ((HibernateProxy) object).getHibernateLazyInitializer();
    return lazyInitializer.getPersistentClass();
  } else {
    return object.getClass();
  }
}

I found out, it is easier than I thought: just call getSuperclass() on the proxied class to obtain the unproxied, original class. I'm not sure how general this is, but it appears to work.

Tags:

Java

Hibernate