View Javadoc
1   /*
2    *    Copyright 2009-2026 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.executor.loader.javassist;
17  
18  import java.lang.reflect.Method;
19  import java.util.List;
20  import java.util.Map;
21  import java.util.Set;
22  import java.util.concurrent.locks.ReentrantLock;
23  
24  import javassist.util.proxy.MethodHandler;
25  import javassist.util.proxy.Proxy;
26  import javassist.util.proxy.ProxyFactory;
27  
28  import org.apache.ibatis.executor.ErrorContext;
29  import org.apache.ibatis.executor.ExecutorException;
30  import org.apache.ibatis.executor.loader.AbstractEnhancedDeserializationProxy;
31  import org.apache.ibatis.executor.loader.AbstractSerialStateHolder;
32  import org.apache.ibatis.executor.loader.ResultLoaderMap;
33  import org.apache.ibatis.executor.loader.WriteReplaceInterface;
34  import org.apache.ibatis.io.Resources;
35  import org.apache.ibatis.logging.Log;
36  import org.apache.ibatis.logging.LogFactory;
37  import org.apache.ibatis.reflection.ExceptionUtil;
38  import org.apache.ibatis.reflection.factory.ObjectFactory;
39  import org.apache.ibatis.reflection.property.PropertyCopier;
40  import org.apache.ibatis.reflection.property.PropertyNamer;
41  import org.apache.ibatis.session.Configuration;
42  
43  /**
44   * @author Eduardo Macarron
45   */
46  public class JavassistProxyFactory implements org.apache.ibatis.executor.loader.ProxyFactory {
47  
48    private static final String FINALIZE_METHOD = "finalize";
49    private static final String WRITE_REPLACE_METHOD = "writeReplace";
50  
51    public JavassistProxyFactory() {
52      try {
53        Resources.classForName("javassist.util.proxy.ProxyFactory");
54      } catch (Throwable e) {
55        throw new IllegalStateException(
56            "Cannot enable lazy loading because Javassist is not available. Add Javassist to your classpath.", e);
57      }
58    }
59  
60    @Override
61    public Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration,
62        ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
63      return EnhancedResultObjectProxyImpl.createProxy(target, lazyLoader, configuration, objectFactory,
64          constructorArgTypes, constructorArgs);
65    }
66  
67    public Object createDeserializationProxy(Object target, Map<String, ResultLoaderMap.LoadPair> unloadedProperties,
68        ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
69      return EnhancedDeserializationProxyImpl.createProxy(target, unloadedProperties, objectFactory, constructorArgTypes,
70          constructorArgs);
71    }
72  
73    static Object createStaticProxy(Class<?> type, MethodHandler callback, List<Class<?>> constructorArgTypes,
74        List<Object> constructorArgs) {
75  
76      ProxyFactory enhancer = new ProxyFactory();
77      enhancer.setSuperclass(type);
78  
79      try {
80        type.getDeclaredMethod(WRITE_REPLACE_METHOD);
81        // ObjectOutputStream will call writeReplace of objects returned by writeReplace
82        if (LogHolder.log.isDebugEnabled()) {
83          LogHolder.log.debug(WRITE_REPLACE_METHOD + " method was found on bean " + type + ", make sure it returns this");
84        }
85      } catch (NoSuchMethodException e) {
86        enhancer.setInterfaces(new Class[] { WriteReplaceInterface.class });
87      } catch (SecurityException e) {
88        // nothing to do here
89      }
90  
91      Object enhanced;
92      Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]);
93      Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]);
94      try {
95        enhanced = enhancer.create(typesArray, valuesArray);
96      } catch (Exception e) {
97        throw new ExecutorException("Error creating lazy proxy.  Cause: " + e, e);
98      }
99      ((Proxy) enhanced).setHandler(callback);
100     return enhanced;
101   }
102 
103   private static class EnhancedResultObjectProxyImpl implements MethodHandler {
104     private final Class<?> type;
105     private final ResultLoaderMap lazyLoader;
106     private final boolean aggressive;
107     private final Set<String> lazyLoadTriggerMethods;
108     private final ObjectFactory objectFactory;
109     private final List<Class<?>> constructorArgTypes;
110     private final List<Object> constructorArgs;
111     private final ReentrantLock lock = new ReentrantLock();
112 
113     private EnhancedResultObjectProxyImpl(Class<?> type, ResultLoaderMap lazyLoader, Configuration configuration,
114         ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
115       this.type = type;
116       this.lazyLoader = lazyLoader;
117       this.aggressive = configuration.isAggressiveLazyLoading();
118       this.lazyLoadTriggerMethods = configuration.getLazyLoadTriggerMethods();
119       this.objectFactory = objectFactory;
120       this.constructorArgTypes = constructorArgTypes;
121       this.constructorArgs = constructorArgs;
122     }
123 
124     public static Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration,
125         ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
126       final Class<?> type = target.getClass();
127       EnhancedResultObjectProxyImpl callback = new EnhancedResultObjectProxyImpl(type, lazyLoader, configuration,
128           objectFactory, constructorArgTypes, constructorArgs);
129       Object enhanced = createStaticProxy(type, callback, constructorArgTypes, constructorArgs);
130       PropertyCopier.copyBeanProperties(type, target, enhanced);
131       return enhanced;
132     }
133 
134     @Override
135     public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) throws Throwable {
136       final String methodName = method.getName();
137       lock.lock();
138       try {
139         if (WRITE_REPLACE_METHOD.equals(methodName)) {
140           Object original;
141           if (constructorArgTypes.isEmpty()) {
142             original = objectFactory.create(type);
143           } else {
144             original = objectFactory.create(type, constructorArgTypes, constructorArgs);
145           }
146           PropertyCopier.copyBeanProperties(type, enhanced, original);
147           if (!lazyLoader.isEmpty()) {
148             return new JavassistSerialStateHolder(original, lazyLoader.getProperties(), objectFactory,
149                 constructorArgTypes, constructorArgs);
150           } else {
151             return original;
152           }
153         }
154         if (!lazyLoader.isEmpty() && !FINALIZE_METHOD.equals(methodName)) {
155           if (aggressive || lazyLoadTriggerMethods.contains(methodName)) {
156             lazyLoader.loadAll();
157           } else if (PropertyNamer.isSetter(methodName)) {
158             final String property = PropertyNamer.methodToProperty(methodName);
159             lazyLoader.remove(property);
160           } else if (PropertyNamer.isGetter(methodName)) {
161             final String property = PropertyNamer.methodToProperty(methodName);
162             if (lazyLoader.hasLoader(property)) {
163               lazyLoader.load(property);
164             }
165           }
166         }
167         return methodProxy.invoke(enhanced, args);
168       } catch (Throwable t) {
169         throw ExceptionUtil.unwrapThrowable(t);
170       } finally {
171         lock.unlock();
172         ErrorContext.instance().reset();
173       }
174     }
175   }
176 
177   private static class EnhancedDeserializationProxyImpl extends AbstractEnhancedDeserializationProxy
178       implements MethodHandler {
179 
180     private EnhancedDeserializationProxyImpl(Class<?> type, Map<String, ResultLoaderMap.LoadPair> unloadedProperties,
181         ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
182       super(type, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
183     }
184 
185     public static Object createProxy(Object target, Map<String, ResultLoaderMap.LoadPair> unloadedProperties,
186         ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
187       final Class<?> type = target.getClass();
188       EnhancedDeserializationProxyImpl callback = new EnhancedDeserializationProxyImpl(type, unloadedProperties,
189           objectFactory, constructorArgTypes, constructorArgs);
190       Object enhanced = createStaticProxy(type, callback, constructorArgTypes, constructorArgs);
191       PropertyCopier.copyBeanProperties(type, target, enhanced);
192       return enhanced;
193     }
194 
195     @Override
196     public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) throws Throwable {
197       final Object o = super.invoke(enhanced, method, args);
198       return o instanceof AbstractSerialStateHolder ? o : methodProxy.invoke(o, args);
199     }
200 
201     @Override
202     protected AbstractSerialStateHolder newSerialStateHolder(Object userBean,
203         Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
204         List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
205       return new JavassistSerialStateHolder(userBean, unloadedProperties, objectFactory, constructorArgTypes,
206           constructorArgs);
207     }
208   }
209 
210   private static class LogHolder {
211     private static final Log log = LogFactory.getLog(JavassistProxyFactory.class);
212   }
213 
214 }