|
27 | 27 | import org.dizitart.no2.exceptions.NotIdentifiableException; |
28 | 28 | import org.dizitart.no2.mapper.NitriteMapper; |
29 | 29 | import org.dizitart.no2.objects.*; |
| 30 | +import org.objenesis.Objenesis; |
30 | 31 | import org.objenesis.ObjenesisStd; |
| 32 | +import org.objenesis.instantiator.ObjectInstantiator; |
31 | 33 |
|
32 | 34 | import java.lang.reflect.Field; |
33 | 35 | import java.util.*; |
|
36 | 38 | import static org.dizitart.no2.exceptions.ErrorCodes.*; |
37 | 39 | import static org.dizitart.no2.exceptions.ErrorMessage.*; |
38 | 40 | import static org.dizitart.no2.objects.filters.ObjectFilters.eq; |
39 | | -import static org.dizitart.no2.util.ReflectionUtils.findAnnotations; |
40 | | -import static org.dizitart.no2.util.ReflectionUtils.getField; |
41 | | -import static org.dizitart.no2.util.ReflectionUtils.getFieldsUpto; |
| 41 | +import static org.dizitart.no2.util.ReflectionUtils.*; |
42 | 42 | import static org.dizitart.no2.util.StringUtils.isNullOrEmpty; |
43 | | -import static org.dizitart.no2.util.ValidationUtils.notEmpty; |
44 | | -import static org.dizitart.no2.util.ValidationUtils.notNull; |
45 | | -import static org.dizitart.no2.util.ValidationUtils.validateObjectIndexField; |
| 43 | +import static org.dizitart.no2.util.ValidationUtils.*; |
46 | 44 |
|
47 | 45 | /** |
48 | 46 | * A utility class for {@link Object}. |
|
53 | 51 | @UtilityClass |
54 | 52 | @Slf4j |
55 | 53 | public class ObjectUtils { |
| 54 | + private static Map<String, ObjectInstantiator> constructorCache = new HashMap<>(); |
| 55 | + private static Objenesis objenesis = new ObjenesisStd(); |
| 56 | + |
56 | 57 | /** |
57 | 58 | * Generates the name of an {@link org.dizitart.no2.objects.ObjectRepository}. |
58 | 59 | * |
@@ -215,11 +216,20 @@ public static boolean isKeyedObjectStore(String collectionName) { |
215 | 216 | } |
216 | 217 | } |
217 | 218 |
|
| 219 | + @SuppressWarnings("unchecked") |
218 | 220 | public static <T> T newInstance(Class<T> type) { |
219 | 221 | try { |
220 | | - return type.newInstance(); |
| 222 | + String clazz = type.getName(); |
| 223 | + ObjectInstantiator instantiator = constructorCache.get(clazz); |
| 224 | + if (instantiator == null) { |
| 225 | + instantiator = objenesis.getInstantiatorOf(type); |
| 226 | + constructorCache.put(clazz, instantiator); |
| 227 | + } |
| 228 | + |
| 229 | + return (T) instantiator.newInstance(); |
221 | 230 | } catch (Exception e) { |
222 | | - return new ObjenesisStd().newInstance(type); |
| 231 | + log.error("Error while creating instance of " + type.getName(), e); |
| 232 | + return null; |
223 | 233 | } |
224 | 234 | } |
225 | 235 |
|
|
0 commit comments