In our project we have a part of code that does things based on the class of the passed object. Something like this:
public class A { }
public class B extends A { }
public class Manager {
public void manageA(A obj) {
if(A.class.equals(obj.getClass()) {
//do stuff
} else if(B.class.equals(obj.getClass()) {
//do other stuff
}
}
}
Now, A and B are Hibernate entities. Sometimes it happens the method manageA receives a proxied object and it fails to do stuff the way it's implemented. So we added a Hibernate.unproxy
to get the unproxied object.
public void manageA(A obj) {
obj = (A) Hibernate.unproxy(obj);
if(A.class.equals(obj.getClass()) {
//do stuff
} else if(B.class.equals(obj.getClass()) {
//do other stuff
}
}
But I was afraid this might have some side effects, that is something that could work with a proxied object does not work anymore. I have noticed, by debugging, that when unproxing the object I lose the "handler" attribute (which is from Hibernate) but I don't know what it does or if Hibernate still handles its stuff in other ways.
I am aware i can just do this
public void manageA(A obj) {
Class<? extends A> clazz = (A) Hibernate.unproxy(obj).getClass();
if(A.class.equals(clazz) {
//do stuff
} else if(B.class.equals(clazz) {
//do other stuff
}
}
leaving the proxied object untouched. But I think whether or not unproxing an Hibernate object has some side effects it's something worth knowing for the future.
It's worth mentioning that I am not afraid of what happens outside the method but what might happen inside the method itself (let's say it calls save or refresh from a Spring Data JPA repository and something that could work with a proxied object does not work with an unproxied object)