update ReferenceFactory method, remove instantiation
[cdmlib.git] / cdmlib-model / src / main / java / eu / etaxonomy / cdm / hibernate / HibernateProxyHelper.java
1 /**
2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9
10 package eu.etaxonomy.cdm.hibernate;
11
12 import org.apache.log4j.Logger;
13 import org.hibernate.proxy.HibernateProxy;
14 import org.hibernate.proxy.LazyInitializer;
15
16 /**
17 * @author a.mueller
18 * @created 03.03.2009
19 * @version 1.0
20 */
21 public class HibernateProxyHelper {
22 @SuppressWarnings("unused")
23 private static final Logger logger = Logger.getLogger(HibernateProxyHelper.class);
24
25
26 // ************************** Hibernate proxies *******************/
27 /* (non-Javadoc)
28 * @see eu.etaxonomy.cdm.model.common.IProxyHelper#deproxy(java.lang.Object, java.lang.Class)
29 */
30 public static <T> T deproxy(Object object, Class<T> clazz) throws ClassCastException {
31 if (object instanceof HibernateProxy) {
32 return clazz.cast(((HibernateProxy) object).getHibernateLazyInitializer().getImplementation());
33 } else {
34 return clazz.cast(object);
35 }
36 }
37
38 /**
39 * Unwrap the target instance from the proxy.
40 */
41 public static Object deproxy(Object object){
42 if(object instanceof HibernateProxy) {
43 LazyInitializer lazyInitializer = ((HibernateProxy)object).getHibernateLazyInitializer();
44 return lazyInitializer.getImplementation();
45 } else {
46 return object;
47 }
48 }
49
50 /* (non-Javadoc)
51 * @see eu.etaxonomy.cdm.model.common.IProxyHelper#isInstanceOf(java.lang.Object, java.lang.Class)
52 */
53 public static boolean isInstanceOf(Object object, Class clazz) throws ClassCastException {
54 if (clazz == null){
55 return false;
56 }
57 if (object instanceof HibernateProxy) {
58 Object impl = ((HibernateProxy) object).getHibernateLazyInitializer().getImplementation();
59 Class implClass = impl.getClass();
60 return clazz.isAssignableFrom(implClass);
61 } else {
62 return clazz.isAssignableFrom(object.getClass());
63 }
64 }
65
66 /**
67 * Get the class of an instance or the underlying class
68 * of a proxy (without initializing the proxy!). It is
69 * almost always better to use the entity name!
70 *
71 * delegates calls to {@link org.hibernate.proxy.HibernateProxyHelper}
72 */
73 public static Class getClassWithoutInitializingProxy(Object object) {
74 return org.hibernate.proxy.HibernateProxyHelper.getClassWithoutInitializingProxy(object);
75 }
76 }