I've been experimenting on removing Hibernate specific details from entity pojo's (e.g. when I need to serialize them and send to remote machines), and following is the code I came up with. Its 'initializeAndUnproxy()' is taken from one of the answers that Bozho gave: Converting Hibernate proxy to real object and I modified it to call a recursive method in it.
I would like your comments on this code about its shortcomings. E.g. it won't remove 'PersistentSet' kind of types from it. So what improvements would you suggest?
static <T> T initializeAndUnproxy(T entity) throws IllegalArgumentException, IllegalAccessException
{
if(entity == null)
{
throw new NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
T ret = entity;
if(entity instanceof HibernateProxy)
{
ret = (T)((HibernateProxy)entity).getHibernateLazyInitializer().getImplementation();
initializeRecursively(ret);
}
return ret;
}
static void initializeRecursively(Object entity) throws IllegalArgumentException, IllegalAccessException
{
Class<?> clazz = entity.getClass();
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields)
{
field.setAccessible(true);
Object obj = field.get(entity);
Hibernate.initialize(obj);
if(obj instanceof HibernateProxy)
{
obj = ((HibernateProxy)obj).getHibernateLazyInitializer().getImplementation();
field.set(entity, obj);
initializeRecursively(obj);
}
if(obj instanceof LazyInitializer)
{
obj = ((LazyInitializer)obj).getImplementation();
initializeRecursively(obj);
}
}
}