• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

burningwave / reflection / #97

27 Nov 2026 08:15PM UTC coverage: 74.528%. Remained the same
#97

push

Roberto-Gentili
Set the version to 4.6.0-SNAPSHOT. Releasing new version

790 of 1060 relevant lines covered (74.53%)

0.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.52
/src/main/java/org/burningwave/reflection/Constructors.java
1
/*
2
 * This file is part of Burningwave Reflection.
3
 *
4
 * Author: Roberto Gentili
5
 *
6
 * Hosted at: https://github.com/burningwave/reflection
7
 *
8
 * --
9
 *
10
 * The MIT License (MIT)
11
 *
12
 * Copyright (c) 2022 Roberto Gentili
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
15
 * documentation files (the "Software"), to deal in the Software without restriction, including without
16
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
17
 * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
18
 * conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all copies or substantial
21
 * portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
24
 * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
25
 * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
26
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
27
 * OR OTHER DEALINGS IN THE SOFTWARE.
28
 */
29
package org.burningwave.reflection;
30

31

32
import java.lang.invoke.MethodHandle;
33
import java.lang.invoke.MethodHandles;
34
import java.lang.invoke.MethodType;
35
import java.lang.reflect.Constructor;
36
import java.util.ArrayList;
37
import java.util.Arrays;
38
import java.util.Collection;
39
import java.util.stream.Collectors;
40

41
import org.burningwave.Classes;
42
import org.burningwave.Executor;
43
import org.burningwave.Throwables;
44

45

46
/**
47
 * Finds constructors and creates objects through them, also when they are not accessible. The constructors are searched
48
 * only in the given class, among the ones whose parameters accept the arguments, and made accessible; the found
49
 * constructors and their method handles are cached:
50
 * <pre>{@code
51
 * MyClass object = Constructors.INSTANCE.newInstanceOf(MyClass.class, "argument", 1);
52
 * }</pre>
53
 * A constructor with a variable arity parameter accepts its last arguments both as an array and as separate values.
54
 */
55
@SuppressWarnings("unchecked")
56
public class Constructors extends Members.Handler.OfExecutable<Constructor<?>, ConstructorCriteria>  {
57
        /**
58
         * The instance of this class.
59
         */
60
        public final static Constructors INSTANCE;
61

62
        static {
63
                INSTANCE = new Constructors();
1 ✔
64
        }
1 ✔
65

66
        private Constructors() {}
1 ✔
67

68
        /**
69
         * Returns all the constructors of a class, made accessible. The result is cached.
70
         *
71
         * @param targetClass the class
72
         * @return the constructors
73
         */
74
        public Collection<Constructor<?>> findAllAndMakeThemAccessible(
75
                Class<?> targetClass
76
        ) {
77
                Collection<Constructor<?>> members = Cache.INSTANCE.uniqueKeyForConstructors.getOrUploadIfAbsent(
×
78
                                getCacheKey(targetClass, Members.ALL_FOR_CLASS), () -> {
×
79
                                return findAllAndApply(
×
80
                                        ConstructorCriteria.withoutConsideringParentClasses(), targetClass, (member) ->
×
81
                                        setAccessible(member, true)
×
82
                                );
83
                        }
84
                );
85
                return members;
×
86
        }
87

88
        /**
89
         * Returns the constructors of a class whose parameters accept arguments of the given types, made accessible: a
90
         * {@code null} type matches any parameter and, without types, the constructors without parameters and the ones with
91
         * only a variable arity parameter are returned. The result is cached.
92
         *
93
         * @param targetClass the class
94
         * @param inputParameterTypesOrSubTypes the types of the arguments
95
         * @return the constructors
96
         */
97
        public Collection<Constructor<?>> findAllAndMakeThemAccessible(
98
                Class<?> targetClass,
99
                Class<?>... inputParameterTypesOrSubTypes
100
        ) {
101
                String cacheKey = getCacheKey(targetClass, Members.ALL_FOR_CLASS + " by input parameters assignable from", inputParameterTypesOrSubTypes);
1 ✔
102
                return Cache.INSTANCE.uniqueKeyForConstructors.getOrUploadIfAbsent(cacheKey, () -> {
1 ✔
103
                        ConstructorCriteria criteria = ConstructorCriteria.withoutConsideringParentClasses().parameterTypesAreAssignableFrom(inputParameterTypesOrSubTypes);
1 ✔
104
                        if (inputParameterTypesOrSubTypes != null && inputParameterTypesOrSubTypes.length == 0) {
1 ✔
105
                                criteria.or().parameter((parameters, idx) -> parameters.length == 1 && parameters[0].isVarArgs());
1 ✔
106
                        }
107
                        return findAllAndApply(
1 ✔
108
                                criteria,
109
                                targetClass,
110
                                (member) ->
111
                                        setAccessible(member, true)
1 ✔
112
                        );
113
                });
114
        }
115

116
        /**
117
         * Returns a method handle for the constructor chosen as {@link #findFirstAndMakeItAccessible(Class, Class...)}
118
         * does.
119
         *
120
         * @param targetClass the class
121
         * @param inputParameterTypesOrSubTypes the types of the arguments
122
         * @return the method handle
123
         */
124
        public MethodHandle findDirectHandle(Class<?> targetClass, Class<?>... inputParameterTypesOrSubTypes) {
125
                return findDirectHandleBox(targetClass, inputParameterTypesOrSubTypes).getHandler();
×
126
        }
127

128
        /**
129
         * Returns the first constructor of a class whose parameters accept arguments of the given types, made accessible:
130
         * if more constructors match, the first one whose parameter types are exactly the given ones, primitive types and
131
         * their wrappers being equal, is preferred.
132
         *
133
         * @param targetClass the class
134
         * @param inputParameterTypesOrSubTypes the types of the arguments
135
         * @return the constructor, or {@code null} if no constructor matches
136
         */
137
        public Constructor<?> findFirstAndMakeItAccessible(Class<?> targetClass, Class<?>... inputParameterTypesOrSubTypes) {
138
                Collection<Constructor<?>> members = findAllAndMakeThemAccessible(targetClass, inputParameterTypesOrSubTypes);
1 ✔
139
                if (members.size() == 1) {
1 ✔
140
                        return members.stream().findFirst().get();
1 ✔
141
                } else if (members.size() > 1) {
×
142
                        Collection<Constructor<?>> membersThatMatch = searchForExactMatch(members, inputParameterTypesOrSubTypes);
×
143
                        if (!membersThatMatch.isEmpty()) {
×
144
                                return membersThatMatch.stream().findFirst().get();
×
145
                        }
146
                        return members.stream().findFirst().get();
×
147
                }
148
                return null;
×
149
        }
150

151
        /**
152
         * Returns the only constructor of a class whose parameters accept arguments of the given types, made accessible. If
153
         * more constructors match, it returns the only one whose parameter types are exactly the given ones and, if there
154
         * is not just one, it throws an {@link Exception}, even though it does not declare it.
155
         *
156
         * @param targetClass the class
157
         * @param argumentTypes the types of the arguments
158
         * @return the constructor, or {@code null} if no constructor matches
159
         */
160
        public Constructor<?> findOneAndMakeItAccessible(Class<?> targetClass, Class<?>... argumentTypes) {
161
                Collection<Constructor<?>> members = findAllAndMakeThemAccessible(targetClass, argumentTypes);
1 ✔
162
                if (members.size() == 1) {
1 ✔
163
                        return members.stream().findFirst().get();
1 ✔
164
                } else if (members.size() > 1) {
×
165
                        Collection<Constructor<?>> membersThatMatch = searchForExactMatch(members, argumentTypes);
×
166
                        if (membersThatMatch.size() == 1) {
×
167
                                return membersThatMatch.stream().findFirst().get();
×
168
                        }
169
                        Throwables.INSTANCE.throwException(
×
170
                                "Found more than one of constructor with argument types {} in {} class",
171
                                String.join(", ", Arrays.asList(argumentTypes).stream().map(cls -> cls.getName()).collect(Collectors.toList())),
×
172
                                targetClass.getName()
×
173
                        );
174
                }
175
                return null;
×
176
        }
177

178
        /**
179
         * Creates an object of a class through the constructor chosen by the types of the arguments as
180
         * {@link #findFirstAndMakeItAccessible(Class, Class...)} does. The constructor is invoked through its method
181
         * handle, see {@link #findDirectHandle(Class, Class...)}, and, if that fails, through
182
         * {@link Facade#newInstance(Constructor, Object...)}. If there is no such constructor, this method throws an
183
         * {@link Exception}, even though it does not declare it.
184
         *
185
         * @param <T> the type of the object
186
         * @param targetClass the class
187
         * @param arguments the arguments
188
         * @return the new object
189
         */
190
        public <T> T newInstanceOf(
191
                Class<?> targetClass,
192
                Object... arguments
193
        ) {
194
                return Executor.getFirst(
1 ✔
195
                        () -> {
196
                                Class<?>[] argsType = Classes.INSTANCE.retrieveFrom(arguments);
1 ✔
197
                                Members.Handler.OfExecutable.Box<Constructor<?>> methodHandleBox = findDirectHandleBox(targetClass, argsType);
1 ✔
198
                                return Executor.get(() -> {
1 ✔
199
                                                Constructor<?> ctor = methodHandleBox.getExecutable();
1 ✔
200
                                                return (T)methodHandleBox.getHandler().invokeWithArguments(
1 ✔
201
                                                        getFlatArgumentList(ctor, ArrayList::new, arguments)
1 ✔
202
                                                );
203
                                        }
204
                                );
205
                        }, () -> {
206
                                Constructor<?> ctor = findFirstAndMakeItAccessible(targetClass, Classes.INSTANCE.retrieveFrom(arguments));
1 ✔
207
                                if (ctor == null) {
1 ✔
208
                                        Throwables.INSTANCE.throwException("Constructor not found in {}", targetClass.getName());
×
209
                                }
210
                                return (T)Facade.INSTANCE.newInstance(
1 ✔
211
                                        ctor,
212
                                        getArgumentArray(
1 ✔
213
                                                ctor,
214
                                                this::getArgumentListWithArrayForVarArgs,
215
                                                ArrayList::new,
216
                                                arguments
217
                                        )
218
                                );
219
                        }
220
                );
221

222
        }
223

224
        @Override
225
        MethodHandle retrieveMethodHandle(MethodHandles.Lookup consulter, Constructor<?> constructor) throws NoSuchMethodException, IllegalAccessException {
226
                return consulter.findConstructor(
1 ✔
227
                        constructor.getDeclaringClass(),
1 ✔
228
                        MethodType.methodType(void.class, constructor.getParameterTypes())
1 ✔
229
                );
230
        }
231

232
        String retrieveNameForCaching(Class<?> cls) {
233
                return Classes.INSTANCE.retrieveSimpleName(cls.getName());
1 ✔
234
        }
235

236
        @Override
237
        String retrieveNameForCaching(Constructor<?> constructor) {
238
                return retrieveNameForCaching(constructor.getDeclaringClass());
1 ✔
239
        }
240

241
        private Members.Handler.OfExecutable.Box<Constructor<?>> findDirectHandleBox(Class<?> targetClass, Class<?>... inputParameterTypesOrSubTypes) {
242
                String nameForCaching = retrieveNameForCaching(targetClass);
1 ✔
243
                String cacheKey = getCacheKey(targetClass, "equals " + nameForCaching, inputParameterTypesOrSubTypes);
1 ✔
244
                Members.Handler.OfExecutable.Box<Constructor<?>> entry =
1 ✔
245
                        (Box<Constructor<?>>)Cache.INSTANCE.uniqueKeyForExecutableAndMethodHandle.get(cacheKey);
1 ✔
246
                if (entry == null) {
1 ✔
247
                        Constructor<?> ctor = findFirstAndMakeItAccessible(targetClass, inputParameterTypesOrSubTypes);
1 ✔
248
                        entry = findDirectHandleBox(
1 ✔
249
                                ctor, cacheKey
250
                        );
251
                }
252
                return entry;
1 ✔
253
        }
254
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc