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.reflection.factory;
17  
18  import java.io.Serializable;
19  import java.lang.reflect.Constructor;
20  import java.util.ArrayList;
21  import java.util.Collection;
22  import java.util.HashMap;
23  import java.util.HashSet;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Optional;
27  import java.util.Set;
28  import java.util.SortedSet;
29  import java.util.TreeSet;
30  import java.util.stream.Collectors;
31  
32  import org.apache.ibatis.reflection.ReflectionException;
33  import org.apache.ibatis.reflection.Reflector;
34  
35  /**
36   * @author Clinton Begin
37   */
38  public class DefaultObjectFactory implements ObjectFactory, Serializable {
39  
40    private static final long serialVersionUID = -8855120656740914948L;
41  
42    @Override
43    public <T> T create(Class<T> type) {
44      return create(type, null, null);
45    }
46  
47    @SuppressWarnings("unchecked")
48    @Override
49    public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
50      Class<?> classToCreate = resolveInterface(type);
51      // we know types are assignable
52      return (T) instantiateClass(classToCreate, constructorArgTypes, constructorArgs);
53    }
54  
55    private <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
56      try {
57        Constructor<T> constructor;
58        if (constructorArgTypes == null || constructorArgs == null) {
59          constructor = type.getDeclaredConstructor();
60          try {
61            return constructor.newInstance();
62          } catch (IllegalAccessException e) {
63            if (Reflector.canControlMemberAccessible()) {
64              constructor.setAccessible(true);
65              return constructor.newInstance();
66            }
67            throw e;
68          }
69        }
70        constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[0]));
71        try {
72          return constructor.newInstance(constructorArgs.toArray(new Object[0]));
73        } catch (IllegalAccessException e) {
74          if (Reflector.canControlMemberAccessible()) {
75            constructor.setAccessible(true);
76            return constructor.newInstance(constructorArgs.toArray(new Object[0]));
77          }
78          throw e;
79        }
80      } catch (Exception e) {
81        String argTypes = Optional.ofNullable(constructorArgTypes).orElseGet(List::of).stream().map(Class::getSimpleName)
82            .collect(Collectors.joining(","));
83        String argValues = Optional.ofNullable(constructorArgs).orElseGet(List::of).stream().map(String::valueOf)
84            .collect(Collectors.joining(","));
85        throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values ("
86            + argValues + "). Cause: " + e, e);
87      }
88    }
89  
90    protected Class<?> resolveInterface(Class<?> type) {
91      Class<?> classToCreate;
92      if (type == List.class || type == Collection.class || type == Iterable.class) {
93        classToCreate = ArrayList.class;
94      } else if (type == Map.class) {
95        classToCreate = HashMap.class;
96      } else if (type == SortedSet.class) { // issue #510 Collections Support
97        classToCreate = TreeSet.class;
98      } else if (type == Set.class) {
99        classToCreate = HashSet.class;
100     } else {
101       classToCreate = type;
102     }
103     return classToCreate;
104   }
105 
106   @Override
107   public <T> boolean isCollection(Class<T> type) {
108     return Collection.class.isAssignableFrom(type);
109   }
110 
111 }