• 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

70.33
/src/main/java/org/burningwave/reflection/Facade.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
import java.lang.invoke.MethodHandle;
32
import java.lang.invoke.MethodHandles;
33
import java.lang.invoke.MethodHandles.Lookup;
34
import java.lang.invoke.MethodType;
35
import java.lang.reflect.AccessibleObject;
36
import java.lang.reflect.Constructor;
37
import java.lang.reflect.Field;
38
import java.lang.reflect.Method;
39
import java.util.AbstractMap;
40
import java.util.ArrayList;
41
import java.util.Collection;
42
import java.util.Collections;
43
import java.util.LinkedHashMap;
44
import java.util.Map;
45

46
import org.burningwave.Executor;
47
import org.burningwave.Strings;
48
import org.burningwave.Throwables;
49
import org.burningwave.ThrowingBiConsumer;
50
import org.burningwave.ThrowingBiFunction;
51
import org.burningwave.ThrowingFunction;
52
import org.burningwave.ThrowingTriConsumer;
53
import org.burningwave.ThrowingTriFunction;
54

55
/**
56
 * The access point of the library to the reflection of the JVM: it retrieves the members declared by a class, makes
57
 * them accessible, reads and writes the fields, invokes the methods and the constructors and supplies a lookup with
58
 * full access to a class. Each operation is tried through the JVM driver of ToolFactory, when it is enabled, then
59
 * through the reflection API and then through the reflection API after making the member accessible: the first way that
60
 * succeeds gives the result and, if all of them fail, the exception of the last one is thrown, even though the methods
61
 * do not declare it.
62
 * <p>
63
 * The JVM driver is enabled by default and is created when this class is initialized: if it cannot be created, for
64
 * example because ToolFactory JVM Driver is not available, a message is printed on the standard error and only the
65
 * reflection API is used. {@link Configuration#disableDriver()} disables it before the initialization, while
66
 * {@link #disableDriver()} and {@link #enableDriver()} switch it afterwards:
67
 * <pre>{@code
68
 * Facade.Configuration.disableDriver();
69
 * Field[] fields = Facade.INSTANCE.getDeclaredFields(MyClass.class);
70
 * }</pre>
71
 */
72
@SuppressWarnings("unchecked")
73
public class Facade {
74
        /**
75
         * The configuration of {@link Facade}, which must be set before the class {@link Facade} is initialized: after
76
         * that, it cannot be changed.
77
         */
78
        public static final class Configuration {
79

80
                /**
81
                 * The keys of the configuration values.
82
                 */
83
                public static final class Key {
84

85
                        private static final String JVM_DRIVER_ENABLED = "jvm-driver.enabled";
86

87
                        private Key() {}
×
88
                }
89

90
                private static boolean freezed;
91
                private static Map<String, Object> values;
92

93
                static {
94
                        values = new LinkedHashMap<>();
1 ✔
95
                        putConfigurationValue(Configuration.Key.JVM_DRIVER_ENABLED, true);
1 ✔
96
                }
1 ✔
97

98
                private Configuration() {}
×
99

100
                /**
101
                 * Disables the JVM driver, so that {@link Facade} uses only the reflection API. If the class {@link Facade} has
102
                 * already been initialized, this method throws an {@link UnsupportedOperationException}.
103
                 */
104
                public static void disableDriver() {
105
                        putConfigurationValue(Configuration.Key.JVM_DRIVER_ENABLED, false);
×
106
                }
×
107

108
                private static Map<String, Object> freezeAndGet() {
109
                        if (!freezed) {
1 ✔
110
                                values = Collections.unmodifiableMap(Configuration.values);
1 ✔
111
                        }
112
                        return values;
1 ✔
113
                }
114

115
                private static void putConfigurationValue(String key, Object value) {
116
                        try {
117
                                values.put(key, value);
1 ✔
118
                        } catch (UnsupportedOperationException exc) {
×
119
                                throw new UnsupportedOperationException("Cannot add configuration value after that the " + Facade.class.getSimpleName() + " has been initialized");
×
120
                        }
1 ✔
121
                }
1 ✔
122

123
        }
124

125
        /**
126
         * The instance of this class.
127
         */
128
        public static final Facade INSTANCE;
129

130
        private static Object driver;
131

132
        private static ThrowingBiFunction<MethodHandles.Lookup, Class<?>, MethodHandles.Lookup, Throwable> privateLookupIn;
133

134
        static {
135
                if ((boolean)Configuration.freezeAndGet().get(Configuration.Key.JVM_DRIVER_ENABLED)) {
1 ✔
136
                        try {
137
                                driver = io.github.toolfactory.jvm.Driver.Factory.getNewDynamic();
1 ✔
138
                        } catch (Throwable exc) {
×
139
                                System.err.println(Strings.INSTANCE.compile("JVM driver not instantiated: {}", exc.getMessage()));
×
140
                        }
1 ✔
141
                }
142
                MethodHandles.Lookup consulter = MethodHandles.lookup();
1 ✔
143
                MethodHandle privateLookupIn = Executor.getFirst(
1 ✔
144
                        () ->
145
                                consulter.findStatic(
1 ✔
146
                                        MethodHandles.class,
147
                                        "privateLookupIn",
148
                                        MethodType.methodType(MethodHandles.Lookup.class, Class.class, MethodHandles.Lookup.class)
1 ✔
149
                                ),
150
                        () ->
151
                                consulter.findStatic(
1 ✔
152
                                        Class.forName(Facade.class.getPackage().getName() + ".ConsulterHandlerForJava7"),
1 ✔
153
                                        "privateLookupIn",
154
                                        MethodType.methodType(MethodHandles.Lookup.class, Class.class, MethodHandles.Lookup.class)
1 ✔
155
                                )
156
                );
157
                Facade.privateLookupIn = (clazz, cons) ->
1 ✔
158
                        (MethodHandles.Lookup)privateLookupIn.invokeWithArguments(cons, clazz);
1 ✔
159
                INSTANCE = new Facade();
1 ✔
160
        }
1 ✔
161

162
        private Collection<ThrowingBiConsumer<AccessibleObject, Boolean, Throwable>> accessibleSetters;
163
        private Collection<ThrowingBiFunction<Constructor<?>, Object[], Object, Throwable>> constructorInvokers;
164
        private Collection<ThrowingFunction<Class<?>, Constructor<?>[], Throwable>> constructorRetrievers;
165
        private Collection<ThrowingBiFunction<MethodHandles.Lookup, Class<?>, MethodHandles.Lookup, Throwable>> consulterRetrievers;
166
        private Collection<ThrowingFunction<Class<?>, Field[], Throwable>> fieldRetrievers;
167
        private Collection<ThrowingBiFunction<Object, Field, Object, Throwable>> fieldValueRetrievers;
168
        private Collection<ThrowingTriConsumer<Object, Field, Object, Throwable>> fieldValueSetters;
169
        private Collection<ThrowingTriFunction<Object, Method, Object[], Object, Throwable>> methodInvokers;
170

171
        private Collection<ThrowingFunction<Class<?>, Method[], Throwable>> methodRetrievers;
172

173
        private Facade() {
1 ✔
174
                fieldRetrievers = new ArrayList<>();
1 ✔
175
                methodRetrievers = new ArrayList<>();
1 ✔
176
                constructorRetrievers = new ArrayList<>();
1 ✔
177
                accessibleSetters = new ArrayList<>();
1 ✔
178
                fieldValueRetrievers = new ArrayList<>();
1 ✔
179
                fieldValueSetters = new ArrayList<>();
1 ✔
180
                methodInvokers = new ArrayList<>();
1 ✔
181
                constructorInvokers = new ArrayList<>();
1 ✔
182
                consulterRetrievers = new ArrayList<>();
1 ✔
183

184
                init(driver != null);
1 ✔
185
        }
1 ✔
186

187
        private void init(boolean driverEnabled) {
188
                fieldRetrievers.clear();
1 ✔
189
                methodRetrievers.clear();
1 ✔
190
                constructorRetrievers.clear();
1 ✔
191
                accessibleSetters.clear();
1 ✔
192
                fieldValueRetrievers.clear();
1 ✔
193
                fieldValueSetters.clear();
1 ✔
194
                methodInvokers.clear();
1 ✔
195
                constructorInvokers.clear();
1 ✔
196
                consulterRetrievers.clear();
1 ✔
197
                if (driverEnabled) {
1 ✔
198
                        fieldRetrievers.add(clazz ->
1 ✔
199
                                ((io.github.toolfactory.jvm.Driver)driver).getDeclaredFields(clazz)
1 ✔
200
                        );
201
                        methodRetrievers.add(clazz ->
1 ✔
202
                                ((io.github.toolfactory.jvm.Driver)driver).getDeclaredMethods(clazz)
1 ✔
203
                        );
204
                        constructorRetrievers.add(clazz ->
1 ✔
205
                                ((io.github.toolfactory.jvm.Driver)driver).getDeclaredConstructors(clazz)
1 ✔
206
                        );
207
                        accessibleSetters.add((accessibleObject, flag) ->
1 ✔
208
                                ((io.github.toolfactory.jvm.Driver)driver).setAccessible(accessibleObject, flag)
1 ✔
209
                        );
210
                        fieldValueRetrievers.add((target, field) ->
1 ✔
211
                                ((io.github.toolfactory.jvm.Driver)driver).getFieldValue(target, field)
1 ✔
212
                        );
213
                        fieldValueSetters.add((target, field, value) ->
1 ✔
214
                                ((io.github.toolfactory.jvm.Driver)driver).setFieldValue(target, field, value)
1 ✔
215
                        );
216
                        methodInvokers.add((target, method, parameters) ->
1 ✔
217
                                ((io.github.toolfactory.jvm.Driver)driver).invoke(target, method, parameters)
×
218
                        );
219
                        constructorInvokers.add((constructor, parameters) ->
1 ✔
220
                                ((io.github.toolfactory.jvm.Driver)driver).newInstance(constructor, parameters)
×
221
                        );
222
                        consulterRetrievers.add((lookup, clazz) ->
1 ✔
223
                                ((io.github.toolfactory.jvm.Driver)driver).getConsulter(clazz)
1 ✔
224
                        );
225
                }
226
                fieldRetrievers.add(clazz ->
1 ✔
227
                        clazz.getDeclaredFields()
1 ✔
228
                );
229
                methodRetrievers.add(clazz ->
1 ✔
230
                        clazz.getDeclaredMethods()
1 ✔
231
                );
232
                constructorRetrievers.add(clazz ->
1 ✔
233
                        clazz.getDeclaredConstructors()
1 ✔
234
                );
235
                accessibleSetters.add((accessibleObject, flag) ->
1 ✔
236
                        accessibleObject.setAccessible(flag)
1 ✔
237
                );
238
                fieldValueRetrievers.add((target, field) ->
1 ✔
239
                        field.get(target)
1 ✔
240
                );
241
                fieldValueRetrievers.add((target, field) ->
1 ✔
242
                        setAccessible(field, true).get(target)
×
243
                );
244
                fieldValueSetters.add((target, field, value) ->
1 ✔
245
                        field.set(target, value)
1 ✔
246
                );
247
                fieldValueSetters.add((target, field, value) ->
1 ✔
248
                        setAccessible(field, true).set(target, value)
×
249
                );
250
                methodInvokers.add((target, method, parameters) ->
1 ✔
251
                        method.invoke(target, parameters)
1 ✔
252
                );
253
                methodInvokers.add((target, method, parameters) ->
1 ✔
254
                        setAccessible(method, true).invoke(target, parameters)
×
255
                );
256
                constructorInvokers.add((constructor, parameters) ->
1 ✔
257
                        constructor.newInstance(parameters)
1 ✔
258
                );
259
                constructorInvokers.add((constructor, parameters) ->
1 ✔
260
                        setAccessible(constructor, true).newInstance(parameters)
×
261
                );
262
                consulterRetrievers.add((consulter, clazz) ->
1 ✔
263
                        MethodHandles.lookup()
1 ✔
264
                );
265
                consulterRetrievers.add((consulter, clazz) ->
1 ✔
266
                        privateLookupIn.apply(consulter, clazz)
1 ✔
267
                );
268
        }
1 ✔
269

270
        /**
271
         * Returns the JVM driver of ToolFactory.
272
         *
273
         * @param <D> the type of the driver, that is {@code io.github.toolfactory.jvm.Driver}
274
         * @return the driver, or {@code null} if it has not been created
275
         */
276
        public <D> D getDriver() {
277
                return (D)driver;
1 ✔
278
        }
279

280
        /**
281
         * Makes the operations use only the reflection API: the JVM driver is kept and can be enabled again.
282
         *
283
         * @return this object
284
         */
285
        public Facade disableDriver() {
286
                init(false);
1 ✔
287
                return this;
1 ✔
288
        }
289

290
        /**
291
         * Makes the operations use the JVM driver first, creating it if needed. If the driver cannot be created, this
292
         * method throws the exception of its creation.
293
         *
294
         * @return this object
295
         */
296
        public Facade enableDriver() {
297
                if (driver == null) {
×
298
                        driver = io.github.toolfactory.jvm.Driver.Factory.getNewDynamic();
×
299
                }
300
                init(true);
×
301
                return this;
×
302
        }
303

304
        /**
305
         * Clears the caches of the library, which hold the members and the method handles found.
306
         *
307
         * @return this object
308
         */
309
        public Facade clearCache() {
310
                Cache.INSTANCE.clear(true);
1 ✔
311
                return this;
1 ✔
312
        }
313

314
        /**
315
         * Runs a function with a lookup that has full access to a class. The lookups are retrieved, in order, through the
316
         * JVM driver, when it is enabled, through {@link MethodHandles#lookup()} called by this class and through
317
         * {@code MethodHandles.privateLookupIn}: the function is run with each of them until it succeeds and, if it fails
318
         * with all of them, this method throws the exception of the last attempt, even though it does not declare it.
319
         *
320
         * @param <R> the type of the result
321
         * @param cls the class
322
         * @param executor the function, which receives the lookup
323
         * @return the lookup with which the function succeeded, mapped to the result of the function
324
         */
325
        public <R> Map.Entry<MethodHandles.Lookup, R> executeWithConsulter(Class<?> cls, ThrowingFunction<MethodHandles.Lookup, R, ? extends Throwable> executor) {
326
                Throwable exception = null;
1 ✔
327
                MethodHandles.Lookup consulter = null;
1 ✔
328
                for (ThrowingBiFunction<Lookup, Class<?>, Lookup, Throwable> consulterRetriever : consulterRetrievers) {
1 ✔
329
                        try {
330
                                return new AbstractMap.SimpleEntry<>(
1 ✔
331
                                        consulter = consulterRetriever.apply(consulter, cls),
1 ✔
332
                                        executor.apply(consulter)
1 ✔
333
                                );
334
                        } catch (Throwable exc) {
1 ✔
335
                                exception = exc;
1 ✔
336
                        }
337
                }
1 ✔
338
                return Throwables.INSTANCE.throwException(exception);
×
339
        }
340

341
        /**
342
         * Returns the constructors declared by a class, retrieved through the JVM driver, when it is enabled, or through
343
         * the reflection API.
344
         *
345
         * @param <T> the type of the class
346
         * @param clazz the class
347
         * @return the constructors
348
         */
349
        public <T> Constructor<T>[] getDeclaredConstructors(Class<T> clazz) {
350
                Throwable exception = null;
1 ✔
351
                for (ThrowingFunction<Class<?>, Constructor<?>[], Throwable> constructorRetriever : constructorRetrievers) {
1 ✔
352
                        try {
353
                                return (Constructor<T>[])constructorRetriever.apply(clazz);
1 ✔
354
                        } catch (Throwable exc) {
×
355
                                exception = exc;
×
356
                        }
357
                }
×
358
                return Throwables.INSTANCE.throwException(exception);
×
359
        }
360

361
        /**
362
         * Returns the fields declared by a class, retrieved through the JVM driver, when it is enabled, which also returns
363
         * the fields that the reflection API filters out, or through the reflection API.
364
         *
365
         * @param clazz the class
366
         * @return the fields
367
         */
368
        public Field[] getDeclaredFields(Class<?> clazz) {
369
                Throwable exception = null;
1 ✔
370
                for (ThrowingFunction<Class<?>, Field[], Throwable> fieldRetriever : fieldRetrievers) {
1 ✔
371
                        try {
372
                                return fieldRetriever.apply(clazz);
1 ✔
373
                        } catch (Throwable exc) {
×
374
                                exception = exc;
×
375
                        }
376
                }
×
377
                return Throwables.INSTANCE.throwException(exception);
×
378
        }
379

380
        /**
381
         * Returns the methods declared by a class, retrieved through the JVM driver, when it is enabled, which also returns
382
         * the methods that the reflection API filters out, or through the reflection API.
383
         *
384
         * @param clazz the class
385
         * @return the methods
386
         */
387
        public Method[] getDeclaredMethods(Class<?> clazz) {
388
                Throwable exception = null;
1 ✔
389
                for (ThrowingFunction<Class<?>, Method[], Throwable> methodRetriever : methodRetrievers) {
1 ✔
390
                        try {
391
                                return methodRetriever.apply(clazz);
1 ✔
392
                        } catch (Throwable exc) {
×
393
                                exception = exc;
×
394
                        }
395
                }
×
396
                return Throwables.INSTANCE.throwException(exception);
×
397
        }
398

399
        /**
400
         * Returns the value of a field of an object, read through the JVM driver, when it is enabled, or through the
401
         * reflection API, making the field accessible if needed.
402
         *
403
         * @param <T> the type of the value
404
         * @param target the object, or {@code null} for a static field
405
         * @param field the field
406
         * @return the value of the field
407
         */
408
        public <T> T getFieldValue(Object target, Field field) {
409
                Throwable exception = null;
1 ✔
410
                for (ThrowingBiFunction<Object, Field, Object, Throwable> fieldValueRetriever : fieldValueRetrievers) {
1 ✔
411
                        try {
412
                                return (T)fieldValueRetriever.apply(target, field);
1 ✔
413
                        } catch (Throwable exc) {
×
414
                                exception = exc;
×
415
                        }
416
                }
×
417
                return Throwables.INSTANCE.throwException(exception);
×
418
        }
419

420
        /**
421
         * Invokes a method through the JVM driver, when it is enabled, or through the reflection API, making the method
422
         * accessible if needed. A {@code null} array of arguments is passed as an array with a single {@code null} element.
423
         *
424
         * @param <T> the type of the result
425
         * @param target the object, or {@code null} for a static method
426
         * @param method the method
427
         * @param params the arguments
428
         * @return the value returned by the method
429
         */
430
        public <T> T invoke(Object target, Method method, Object[] params) {
431
                if (params == null) {
1 ✔
432
                        params = new Object[] {null};
×
433
                }
434
                Throwable exception = null;
1 ✔
435
                for (ThrowingTriFunction<Object, Method, Object[], Object, Throwable> methodInvoker : methodInvokers) {
1 ✔
436
                        try {
437
                                return (T)methodInvoker.apply(target, method, params);
1 ✔
438
                        } catch (Throwable exc) {
×
439
                                exception = exc;
×
440
                        }
441
                }
×
442
                return Throwables.INSTANCE.throwException(exception);
×
443
        }
444

445
        /**
446
         * Creates an object through a constructor, invoked through the JVM driver, when it is enabled, or through the
447
         * reflection API, making the constructor accessible if needed. A {@code null} array of arguments is passed as an
448
         * array with a single {@code null} element.
449
         *
450
         * @param <T> the type of the object
451
         * @param constructor the constructor
452
         * @param parameters the arguments
453
         * @return the new object
454
         */
455
        public <T> T newInstance(Constructor<T> constructor, Object... parameters) {
456
                if (parameters == null) {
1 ✔
457
                        parameters = new Object[] {null};
×
458
                }
459
                Throwable exception = null;
1 ✔
460
                for (ThrowingBiFunction<Constructor<?>, Object[], Object, Throwable> constructorInvoker : constructorInvokers) {
1 ✔
461
                        try {
462
                                return (T)constructorInvoker.apply(constructor, parameters);
1 ✔
463
                        } catch (Throwable exc) {
×
464
                                exception = exc;
×
465
                        }
466
                }
×
467
                return Throwables.INSTANCE.throwException(exception);
×
468
        }
469

470
        /**
471
         * Sets the accessible flag of a field, a method or a constructor through the JVM driver, when it is enabled, which
472
         * also works when the module system would not allow it, or through the reflection API.
473
         *
474
         * @param <A> the type of the member
475
         * @param accessibleObject the member
476
         * @param flag the value of the flag
477
         * @return the member
478
         */
479
        public <A extends AccessibleObject> A setAccessible(A accessibleObject, boolean flag) {
480
                Throwable exception = null;
1 ✔
481
                for (ThrowingBiConsumer<AccessibleObject, Boolean, Throwable> accessibleSetter : accessibleSetters) {
1 ✔
482
                        try {
483
                                accessibleSetter.accept(accessibleObject, flag);
1 ✔
484
                                return accessibleObject;
1 ✔
485
                        } catch (Throwable exc) {
×
486
                                exception = exc;
×
487
                        }
488
                }
×
489
                return Throwables.INSTANCE.throwException(exception);
×
490
        }
491

492
        /**
493
         * Sets the value of a field of an object through the JVM driver, when it is enabled, which also works on the final
494
         * fields, or through the reflection API, making the field accessible if needed.
495
         *
496
         * @param target the object, or {@code null} for a static field
497
         * @param field the field
498
         * @param value the value
499
         */
500
        public void setFieldValue(Object target, Field field, Object value) {
501
                Throwable exception = null;
1 ✔
502
                for (ThrowingTriConsumer<Object, Field, Object, Throwable> fieldValueSetter : fieldValueSetters) {
1 ✔
503
                        try {
504
                                fieldValueSetter.accept(target, field, value);
1 ✔
505
                                return;
1 ✔
506
                        } catch (Throwable exc) {
×
507
                                exception = exc;
×
508
                        }
509
                }
×
510
                Throwables.INSTANCE.throwException(exception);
×
511
        }
×
512

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