1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package org.apache.ibatis.executor;
17  
18  import java.lang.reflect.Array;
19  import java.util.List;
20  
21  import org.apache.ibatis.reflection.MetaObject;
22  import org.apache.ibatis.reflection.factory.ObjectFactory;
23  import org.apache.ibatis.session.Configuration;
24  
25  
26  
27  
28  public class ResultExtractor {
29    private final Configuration configuration;
30    private final ObjectFactory objectFactory;
31  
32    public ResultExtractor(Configuration configuration, ObjectFactory objectFactory) {
33      this.configuration = configuration;
34      this.objectFactory = objectFactory;
35    }
36  
37    public Object extractObjectFromList(List<Object> list, Class<?> targetType) {
38      Object value = null;
39      if (targetType != null && targetType.isAssignableFrom(list.getClass())) {
40        value = list;
41      } else if (targetType != null && objectFactory.isCollection(targetType)) {
42        value = objectFactory.create(targetType);
43        MetaObject metaObject = configuration.newMetaObject(value);
44        metaObject.addAll(list);
45      } else if (targetType != null && targetType.isArray()) {
46        Class<?> arrayComponentType = targetType.getComponentType();
47        Object array = Array.newInstance(arrayComponentType, list.size());
48        if (arrayComponentType.isPrimitive()) {
49          for (int i = 0; i < list.size(); i++) {
50            Array.set(array, i, list.get(i));
51          }
52          value = array;
53        } else {
54          value = list.toArray((Object[])array);
55        }
56      } else {
57        if (list != null && list.size() > 1) {
58          throw new ExecutorException("Statement returned more than one row, where no more than one was expected.");
59        } else if (list != null && list.size() == 1) {
60          value = list.get(0);
61        }
62      }
63      return value;
64    }
65  }