• 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

67.65
/src/main/java/org/burningwave/reflection/Methods.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.Method;
36
import java.lang.reflect.Modifier;
37
import java.util.ArrayList;
38
import java.util.Arrays;
39
import java.util.Collection;
40
import java.util.List;
41
import java.util.function.Predicate;
42
import java.util.function.Supplier;
43
import java.util.stream.Collectors;
44

45
import org.burningwave.Classes;
46
import org.burningwave.Executor;
47
import org.burningwave.Strings;
48
import org.burningwave.Throwables;
49
import org.burningwave.ThrowingFunction;
50

51
/**
52
 * Finds methods and invokes them, also when they are not accessible. The methods that receive a method name search it
53
 * in the class of the target object, then in its interfaces and superclasses, among the methods whose parameters accept
54
 * the arguments, and make it accessible; the found methods and their method handles are cached:
55
 * <pre>{@code
56
 * String result = Methods.INSTANCE.invoke(object, "privateMethod", "argument");
57
 * Integer sum = Methods.INSTANCE.invokeStatic(Calculator.class, "sum", 1, 2);
58
 * }</pre>
59
 * A method with a variable arity parameter accepts its last arguments both as an array and as separate values.
60
 */
61
@SuppressWarnings("unchecked")
62
public class Methods extends Members.Handler.OfExecutable<Method, MethodCriteria> {
63

64
        /**
65
         * The instance of this class.
66
         */
67
        public final static Methods INSTANCE;
68

69
        static {
70
                INSTANCE = new Methods();
1 ✔
71
        }
1 ✔
72

73
        private Methods(){}
1 ✔
74

75
        /**
76
         * Returns all the methods of a class and of its hierarchy, made accessible. The result is cached.
77
         *
78
         * @param targetClass the class
79
         * @return the methods
80
         */
81
        public Collection<Method> findAllAndMakeThemAccessible(
82
                Class<?> targetClass
83
        ) {
84
                String cacheKey = getCacheKey(targetClass, Members.ALL_FOR_CLASS);
1 ✔
85
                Collection<Method> members = Cache.INSTANCE.uniqueKeyForAllMethods.getOrUploadIfAbsent(
1 ✔
86
                        cacheKey, () -> {
87
                                return findAllAndMakeThemAccessible(
1 ✔
88
                                        MethodCriteria.forEntireClassHierarchy(), targetClass
1 ✔
89
                                );
90
                        }
91
                );
92
                return members;
1 ✔
93
        }
94

95
        /**
96
         * Returns the methods with a given name, in a class and in its hierarchy, whose parameters accept arguments of the
97
         * given types, made accessible: a {@code null} type matches any parameter and, without types, the methods without
98
         * parameters and the ones with only a variable arity parameter are returned. The result is cached.
99
         *
100
         * @param targetClass the class
101
         * @param methodName the name of the methods
102
         * @param inputParameterTypesOrSubTypes the types of the arguments
103
         * @return the methods
104
         */
105
        public Collection<Method> findAllByExactNameAndMakeThemAccessible(
106
                Class<?> targetClass,
107
                String methodName,
108
                Class<?>... inputParameterTypesOrSubTypes
109
        ) {
110
                return findAllByNamePredicateAndMakeThemAccessible(targetClass, "equals " + methodName, methodName::equals, inputParameterTypesOrSubTypes);
1 ✔
111
        }
112

113
        /**
114
         * Returns the methods whose name matches a regular expression, in a class and in its hierarchy, whose parameters
115
         * accept arguments of the given types, made accessible: the types are handled as
116
         * {@link #findAllByExactNameAndMakeThemAccessible(Class, String, Class...)} does. The result is cached.
117
         *
118
         * @param targetClass the class
119
         * @param regEx the regular expression
120
         * @param inputParameterTypesOrSubTypes the types of the arguments
121
         * @return the methods
122
         */
123
        public Collection<Method> findAllByMatchedNameAndMakeThemAccessible(
124
                Class<?> targetClass,
125
                String regEx,
126
                Class<?>... inputParameterTypesOrSubTypes
127
        ) {
128
                return findAllByNamePredicateAndMakeThemAccessible(
×
129
                        targetClass, "match " + regEx,
130
                        name -> name.matches(regEx),
×
131
                        inputParameterTypesOrSubTypes
132
                );
133
        }
134

135
        /**
136
         * Returns a method handle for the method chosen as {@link #findFirstAndMakeItAccessible(Class, String, Class...)}
137
         * does. The method handle of an instance method invokes that very method, even if a subclass overrides it. If there
138
         * is no such method, this method throws a {@link NoSuchMethodException}.
139
         *
140
         * @param targetClass the class
141
         * @param methodName the name of the method
142
         * @param inputParameterTypesOrSubTypes the types of the arguments
143
         * @return the method handle
144
         */
145
        public MethodHandle findDirectHandle(Class<?> targetClass, String methodName, Class<?>... inputParameterTypesOrSubTypes) {
146
                return findDirectHandleBox(targetClass, methodName, inputParameterTypesOrSubTypes).getHandler();
×
147
        }
148

149
        /**
150
         * Returns the first method with a given name, in a class and in its hierarchy, whose parameters accept arguments of
151
         * the given types, made accessible: if more methods match, the first one whose parameter types are exactly the
152
         * given ones, primitive types and their wrappers being equal, is preferred.
153
         *
154
         * @param targetClass the class
155
         * @param memberName the name of the method
156
         * @param inputParameterTypesOrSubTypes the types of the arguments
157
         * @return the method, or {@code null} if no method matches
158
         */
159
        public Method findFirstAndMakeItAccessible(Class<?> targetClass, String memberName, Class<?>... inputParameterTypesOrSubTypes) {
160
                Collection<Method> members = findAllByExactNameAndMakeThemAccessible(targetClass, memberName, inputParameterTypesOrSubTypes);
1 ✔
161
                if (members.size() == 1) {
1 ✔
162
                        return members.stream().findFirst().get();
1 ✔
163
                } else if (members.size() > 1) {
1 ✔
164
                        Collection<Method> membersThatMatch = searchForExactMatch(members, inputParameterTypesOrSubTypes);
1 ✔
165
                        if (!membersThatMatch.isEmpty()) {
1 ✔
166
                                return membersThatMatch.stream().findFirst().get();
1 ✔
167
                        }
168
                        return members.stream().findFirst().get();
1 ✔
169
                }
170
                return null;
×
171
        }
172

173

174
        /**
175
         * Returns the only method with a given name, in a class and in its hierarchy, whose parameters accept arguments of
176
         * the given types, made accessible. If more methods match, it returns the only one whose parameter types are
177
         * exactly the given ones and, if there is not just one, it throws an {@link IllegalArgumentException}.
178
         *
179
         * @param targetClass the class
180
         * @param memberName the name of the method
181
         * @param inputParameterTypesOrSubTypes the types of the arguments
182
         * @return the method, or {@code null} if no method matches
183
         */
184
        public Method findOneAndMakeItAccessible(Class<?> targetClass, String memberName, Class<?>... inputParameterTypesOrSubTypes) {
185
                Collection<Method> members = findAllByExactNameAndMakeThemAccessible(targetClass, memberName, inputParameterTypesOrSubTypes);
×
186
                if (members.size() == 1) {
×
187
                        return members.stream().findFirst().get();
×
188
                } else if (members.size() > 1) {
×
189
                        Collection<Method> membersThatMatch = searchForExactMatch(members, inputParameterTypesOrSubTypes);
×
190
                        if (membersThatMatch.size() == 1) {
×
191
                                return membersThatMatch.stream().findFirst().get();
×
192
                        }
193
                        Throwables.INSTANCE.throwException(
×
194
                                new IllegalArgumentException(
195
                                        Strings.INSTANCE.compile(
×
196
                                                "Found more than one of method named {} with argument types {} in {} hierarchy",
197
                                                memberName,
198
                                                String.join(", ", Arrays.asList(inputParameterTypesOrSubTypes).stream().map(cls -> cls.getName()).collect(Collectors.toList())),
×
199
                                                targetClass.getName()
×
200
                                        )
201
                                )
202
                        );
203
                }
204
                return null;
×
205
        }
206

207
        /**
208
         * Invokes a method through {@link Facade#invoke(Object, Method, Object[])}.
209
         *
210
         * @param <T> the type of the result
211
         * @param target the object, or {@code null} for a static method
212
         * @param method the method
213
         * @param params the arguments
214
         * @return the value returned by the method
215
         */
216
        public <T> T invoke(Object target, Method method, Object... params) {
217
                return Facade.INSTANCE.invoke(target, method, params);
1 ✔
218
        }
219

220
        /**
221
         * Invokes a method of an object, chosen by name and by the types of the arguments as
222
         * {@link #findFirstAndMakeItAccessible(Class, String, Class...)} does. The method is invoked through its method
223
         * handle, see {@link #findDirectHandle(Class, String, Class...)}, and, if that fails, through
224
         * {@link #invoke(Object, Method, Object...)}. If there is no such method, this method throws a
225
         * {@link NoSuchMethodException}.
226
         *
227
         * @param <T> the type of the result
228
         * @param target the object
229
         * @param methodName the name of the method
230
         * @param arguments the arguments
231
         * @return the value returned by the method
232
         */
233
        public <T> T invoke(Object target, String methodName, Object... arguments) {
234
                return Executor.getFirst(() ->
1 ✔
235
                        (T)invokeDirect(
1 ✔
236
                                Classes.INSTANCE.retrieveFrom(target),
1 ✔
237
                                target, methodName, () -> {
238
                                        List<Object> argumentList = new ArrayList<>();
1 ✔
239
                                        argumentList.add(target);
1 ✔
240
                                        return argumentList;
1 ✔
241
                                },
242
                                arguments
243
                        ), () ->
244
                                invoke(
1 ✔
245
                                        Classes.INSTANCE.retrieveFrom(target),
1 ✔
246
                                        null, methodName, method ->
247
                                                invoke(
1 ✔
248
                                                        target, method, getArgumentArray(
1 ✔
249
                                                        method,
250
                                                        this::getArgumentListWithArrayForVarArgs,
251
                                                        ArrayList::new,
252
                                                        arguments
253
                                                )
254
                                        ),
255
                                        arguments
256
                                )
257
                );
258
        }
259

260
        /**
261
         * Invokes a static method of a class, chosen by name and by the types of the arguments, as
262
         * {@link #invoke(Object, String, Object...)} does.
263
         *
264
         * @param <T> the type of the result
265
         * @param targetClass the class
266
         * @param methodName the name of the method
267
         * @param arguments the arguments
268
         * @return the value returned by the method
269
         */
270
        public         <T> T invokeStatic(Class<?> targetClass, String methodName, Object... arguments) {
271
                return Executor.getFirst(
1 ✔
272
                        () ->
273
                                (T)invokeDirect(targetClass, null, methodName, ArrayList::new, arguments),
1 ✔
274
                        () ->
275
                                invoke(
×
276
                                        targetClass, null, methodName, method ->
277
                                                (T)invoke(null,
×
278
                                                        method,
279
                                                        getArgumentArray(
×
280
                                                                method,
281
                                                                this::getArgumentListWithArrayForVarArgs,
282
                                                                ArrayList::new,
283
                                                                arguments
284
                                                        )
285
                                                ),
286
                                        arguments
287
                                )
288
                );
289
        }
290

291

292
        String createGetterMethodNameByFieldPath(String fieldPath) {
293
                String methodName =
×
294
                        "get" + Strings.INSTANCE.capitalizeFirstCharacter(fieldPath);
×
295
                return methodName;
×
296
        }
297

298
        String createSetterMethodNameByFieldPath(String fieldPath) {
299
                String methodName =
×
300
                        "set" + Strings.INSTANCE.capitalizeFirstCharacter(fieldPath);
×
301
                return methodName;
×
302
        }
303

304
        @Override
305
        MethodHandle retrieveMethodHandle(MethodHandles.Lookup consulter, Method method) throws java.lang.NoSuchMethodException, IllegalAccessException {
306
                Class<?> methodDeclaringClass = method.getDeclaringClass();
1 ✔
307
                return !Modifier.isStatic(method.getModifiers())?
1 ✔
308
                        consulter.findSpecial(
1 ✔
309
                                methodDeclaringClass, retrieveNameForCaching(method),
1 ✔
310
                                MethodType.methodType(method.getReturnType(), method.getParameterTypes()),
1 ✔
311
                                methodDeclaringClass
312
                        ):
313
                        consulter.findStatic(
1 ✔
314
                                methodDeclaringClass, retrieveNameForCaching(method),
1 ✔
315
                                MethodType.methodType(method.getReturnType(), method.getParameterTypes())
1 ✔
316
                        );
317
        }
318

319
        @Override
320
        String retrieveNameForCaching(Method method) {
321
                return method.getName();
1 ✔
322
        }
323

324
        private Collection<Method> findAllByNamePredicateAndMakeThemAccessible(
325
                Class<?> targetClass,
326
                String cacheKeyPrefix,
327
                Predicate<String> namePredicate,
328
                Class<?>... inputParameterTypesOrSubTypes
329
        ) {
330
                String cacheKey = getCacheKey(targetClass, cacheKeyPrefix, inputParameterTypesOrSubTypes);
1 ✔
331
                return Cache.INSTANCE.uniqueKeyForAllMethods.getOrUploadIfAbsent(cacheKey, () -> {
1 ✔
332
                        MethodCriteria criteria = MethodCriteria.forEntireClassHierarchy()
1 ✔
333
                                .name(namePredicate)
1 ✔
334
                                .and().parameterTypesAreAssignableFrom(inputParameterTypesOrSubTypes);
1 ✔
335
                        if (inputParameterTypesOrSubTypes != null && inputParameterTypesOrSubTypes.length == 0) {
1 ✔
336
                                criteria = criteria.or(MethodCriteria.forEntireClassHierarchy().name(namePredicate).and().parameter((parameters, idx) -> parameters.length == 1 && parameters[0].isVarArgs()));
1 ✔
337
                        }
338
                        MethodCriteria finalCriteria = criteria;
1 ✔
339
                        return Cache.INSTANCE.uniqueKeyForAllMethods.getOrUploadIfAbsent(cacheKey, () ->
1 ✔
340
                                findAllAndApply(
1 ✔
341
                                                finalCriteria, targetClass, (member) -> {
342
                                                setAccessible(member, true);
1 ✔
343
                                        }
1 ✔
344
                                )
345
                        );
346
                });
347
        }
348

349
        private Members.Handler.OfExecutable.Box<Method> findDirectHandleBox(Class<?> targetClass, String methodName, Class<?>... inputParameterTypesOrSubTypes) {
350
                String cacheKey = getCacheKey(targetClass, "equals " + methodName, inputParameterTypesOrSubTypes);
1 ✔
351
                Members.Handler.OfExecutable.Box<Method> entry =
1 ✔
352
                        (Box<Method>)Cache.INSTANCE.uniqueKeyForExecutableAndMethodHandle.get(cacheKey);
1 ✔
353
                if (entry == null) {
1 ✔
354
                        Method method = findFirstAndMakeItAccessible(targetClass, methodName, inputParameterTypesOrSubTypes);
1 ✔
355
                        if (method == null) {
1 ✔
356
                                Throwables.INSTANCE.throwException(
×
357
                                        new NoSuchMethodException(
358
                                                Strings.INSTANCE.compile(
×
359
                                                        "Method {} not found in {} hierarchy", methodName, targetClass.getName()
×
360
                                                )
361
                                        )
362
                                );
363
                        }
364
                        entry = findDirectHandleBox(
1 ✔
365
                                method, cacheKey
366
                        );
367
                }
368
                return entry;
1 ✔
369
        }
370

371
        private <T> T invoke(Class<?> targetClass, Object target, String methodName, ThrowingFunction<Method, T, Throwable> methodInvoker, Object... arguments) {
372
                return Executor.get(() -> {
1 ✔
373
                        Method method = findFirstAndMakeItAccessible(targetClass, methodName, Classes.INSTANCE.retrieveFrom(arguments));
1 ✔
374
                        if (method == null) {
1 ✔
375
                                Throwables.INSTANCE.throwException(
×
376
                                        new NoSuchMethodException(
377
                                                Strings.INSTANCE.compile(
×
378
                                                        "Method {} not found in {} hierarchy", methodName, targetClass.getName()
×
379
                                                )
380
                                        )
381
                                );
382
                        }
383
                        return methodInvoker.apply(method);
1 ✔
384
                });
385
        }
386

387
        private <T> T invokeDirect(Class<?> targetClass, Object target, String methodName, Supplier<List<Object>> listSupplier,  Object... arguments) {
388
                Class<?>[] argsType = Classes.INSTANCE.retrieveFrom(arguments);
1 ✔
389
                Members.Handler.OfExecutable.Box<Method> methodHandleBox = findDirectHandleBox(targetClass, methodName, argsType);
1 ✔
390
                return Executor.get(() -> {
1 ✔
391
                                Method method = methodHandleBox.getExecutable();
1 ✔
392
                                List<Object> argumentList = getFlatArgumentList(method, listSupplier, arguments);
1 ✔
393
                                return (T)methodHandleBox.getHandler().invokeWithArguments(argumentList);
1 ✔
394
                        }
395
                );
396
        }
397

398
        /**
399
         * Thrown when a method is not found: unlike {@link java.lang.NoSuchMethodException}, it is unchecked.
400
         */
401
        public static class NoSuchMethodException extends RuntimeException {
402

403
                private static final long serialVersionUID = -2912826056405333039L;
404

405
                /**
406
                 * Creates the exception.
407
                 *
408
                 * @param message the detail message
409
                 */
410
                public NoSuchMethodException(String message) {
411
                        super(message);
×
412
                }
×
413

414
        }
415

416
}
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