1 16 package com.ibatis.sqlmap.engine.mapping.result.loader; 17 18 import com.ibatis.common.beans.ClassInfo; 19 import com.ibatis.common.exception.NestedRuntimeException; 20 import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient; 21 22 import java.lang.reflect.InvocationHandler ; 23 import java.lang.reflect.Method ; 24 import java.lang.reflect.Proxy ; 25 import java.sql.SQLException ; 26 import java.util.Collection ; 27 import java.util.List ; 28 29 32 public class LazyResultLoader implements InvocationHandler { 33 34 private static final Class [] LIST_INTERFACES = new Class []{List .class}; 35 36 protected ExtendedSqlMapClient client; 37 protected String statementName; 38 protected Object parameterObject; 39 protected Class targetType; 40 41 protected boolean loaded; 42 protected Object resultObject; 43 44 52 public LazyResultLoader(ExtendedSqlMapClient client, String statementName, Object parameterObject, Class targetType) { 53 this.client = client; 54 this.statementName = statementName; 55 this.parameterObject = parameterObject; 56 this.targetType = targetType; 57 } 58 59 66 public Object loadResult() throws SQLException { 67 if (Collection .class.isAssignableFrom(targetType)) { 68 InvocationHandler handler = new LazyResultLoader(client, statementName, parameterObject, targetType); 69 ClassLoader cl = targetType.getClassLoader(); 70 return Proxy.newProxyInstance(cl, LIST_INTERFACES, handler); 71 } else { 72 return ResultLoader.getResult(client, statementName, parameterObject, targetType); 73 } 74 } 75 76 public Object invoke(Object o, Method method, Object [] objects) throws Throwable { 77 if ("finalize".hashCode() == method.getName().hashCode() 78 && "finalize".equals(method.getName())) { 79 return null; 80 } else { 81 loadObject(); 82 if (resultObject != null) { 83 try { 84 return method.invoke(resultObject, objects); 85 } catch (Throwable t) { 86 throw ClassInfo.unwrapThrowable(t); 87 } 88 } else { 89 return null; 90 } 91 } 92 } 93 94 private synchronized void loadObject() { 95 if (!loaded) { 96 try { 97 loaded = true; 98 resultObject = ResultLoader.getResult(client, statementName, parameterObject, targetType); 99 } catch (SQLException e) { 100 throw new NestedRuntimeException("Error lazy loading result. Cause: " + e, e); 101 } 102 } 103 } 104 105 } 106 | Popular Tags |