Skip to content

Package: InstanceCreator

InstanceCreator

nameinstructionbranchcomplexitylinemethod
InstanceCreator()
M: 7 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 2 C: 0
0%
M: 1 C: 0
0%
createInstance(Class)
M: 22 C: 0
0%
M: 2 C: 0
0%
M: 2 C: 0
0%
M: 6 C: 0
0%
M: 1 C: 0
0%
lambda$createInstance$0(Constructor)
M: 3 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
static {...}
M: 35 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 8 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*
2: * Copyright (c) 2019, 2022 Oracle and/or its affiliates. All rights reserved.
3: *
4: * This program and the accompanying materials are made available under the
5: * terms of the Eclipse Public License v. 2.0 which is available at
6: * http://www.eclipse.org/legal/epl-2.0,
7: * or the Eclipse Distribution License v. 1.0 which is available at
8: * http://www.eclipse.org/org/documents/edl-v10.php.
9: *
10: * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
11: */
12:
13: package org.eclipse.yasson.internal;
14:
15: import java.lang.reflect.Constructor;
16: import java.util.ArrayList;
17: import java.util.HashMap;
18: import java.util.HashSet;
19: import java.util.LinkedList;
20: import java.util.Map;
21: import java.util.TreeMap;
22: import java.util.TreeSet;
23: import java.util.function.Supplier;
24:
25: /**
26: * Creates instances for known types, caches constructors of unknown.
27: * (Constructors of parsed types are stored in {@link org.eclipse.yasson.internal.model.ClassModel}).
28: */
29: public class InstanceCreator {
30:
31: private static final Map<Class<?>, Supplier<?>> CREATORS = new HashMap<>();
32:
33: static {
34: CREATORS.put(ArrayList.class, ArrayList::new);
35: CREATORS.put(LinkedList.class, LinkedList::new);
36: CREATORS.put(HashSet.class, HashSet::new);
37: CREATORS.put(TreeSet.class, TreeSet::new);
38: CREATORS.put(HashMap.class, HashMap::new);
39: CREATORS.put(TreeMap.class, TreeMap::new);
40: }
41:
42: private InstanceCreator() {
43: throw new IllegalStateException("This class should never be instantiated");
44: }
45:
46: /**
47: * Create an instance of the given class with its default constructor.
48: *
49: * @param tClass class to create instance
50: * @param <T> Type of the class/instance
51: * @return crated instance
52: */
53: @SuppressWarnings("unchecked")
54: public static <T> T createInstance(Class<T> tClass) {
55: Supplier<T> creator = (Supplier<T>) CREATORS.get(tClass);
56: //No worries for race conditions here, instance may be replaced during first attempt.
57:• if (creator == null) {
58: Constructor<T> constructor = ReflectionUtils.getDefaultConstructor(tClass, true);
59: creator = () -> ReflectionUtils.createNoArgConstructorInstance(constructor);
60: CREATORS.put(tClass, creator);
61: }
62:
63: return creator.get();
64: }
65:
66: }