• 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

69.23
/src/main/java/org/burningwave/reflection/Fields.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.reflect.Field;
33
import java.lang.reflect.Modifier;
34
import java.util.Collection;
35
import java.util.HashMap;
36
import java.util.Map;
37
import java.util.function.Supplier;
38

39
import org.burningwave.Classes;
40
import org.burningwave.Strings;
41
import org.burningwave.Throwables;
42

43

44

45

46
/**
47
 * Finds fields and reads and writes their values, also when they are not accessible. The methods that receive a field
48
 * name search it in the class of the target object, then in its interfaces and superclasses, and make it accessible;
49
 * the found fields are cached. The values are read and written through {@link Facade}, so through the JVM driver when
50
 * it is enabled, which also works on the final fields:
51
 * <pre>{@code
52
 * String value = Fields.INSTANCE.get(object, "privateField");
53
 * Fields.INSTANCE.set(object, "privateField", "new value");
54
 * Map<Field, ?> allValues = Fields.INSTANCE.getAll(object);
55
 * }</pre>
56
 */
57
public class Fields extends Members.Handler<Field, FieldCriteria> {
58

59
        /**
60
         * The instance of this class.
61
         */
62
        public static final Fields INSTANCE;
63

64
        static {
65
                INSTANCE = new Fields();
1 ✔
66
        }
1 ✔
67

68
        private Fields() {}
1 ✔
69

70
        /**
71
         * Returns all the fields of a class and of its hierarchy, made accessible. The result is cached.
72
         *
73
         * @param targetClass the class
74
         * @return the fields
75
         */
76
        public Collection<Field> findAllAndMakeThemAccessible(
77
                Class<?> targetClass
78
        ) {
79
                String cacheKey = getCacheKey(targetClass, Members.ALL_FOR_CLASS, (Class<?>[])null);
1 ✔
80
                return Cache.INSTANCE.uniqueKeyForAllFields.getOrUploadIfAbsent(
1 ✔
81
                        cacheKey,
82
                        () ->
83
                                findAllAndMakeThemAccessible(
1 ✔
84
                                        FieldCriteria.forEntireClassHierarchy(), targetClass
1 ✔
85
                                )
86
                );
87
        }
88

89
        /**
90
         * Returns all the fields with a given name in a class and in its hierarchy, made accessible. The result is cached.
91
         *
92
         * @param targetClass the class
93
         * @param fieldName the name of the fields
94
         * @return the fields
95
         */
96
        public Collection<Field> findAllByExactNameAndMakeThemAccessible(
97
                Class<?> targetClass,
98
                String fieldName
99
        ) {
100
                return findAllByExactNameAndMakeThemAccessible(targetClass, fieldName, null);
×
101
        }
102

103
        /**
104
         * Returns all the fields with a given name, whose type can hold a value of a given type, in a class and in its
105
         * hierarchy, made accessible. The result is cached.
106
         *
107
         * @param targetClass the class
108
         * @param fieldName the name of the fields
109
         * @param valueType the type of the value, or {@code null} for any type
110
         * @return the fields
111
         */
112
        public Collection<Field> findAllByExactNameAndMakeThemAccessible(
113
                Class<?> targetClass,
114
                String fieldName,
115
                Class<?> valueType
116
        ) {
117
                String cacheKey = getCacheKey(targetClass, "equals " + fieldName, valueType);
1 ✔
118
                return Cache.INSTANCE.uniqueKeyForAllFields.getOrUploadIfAbsent(
1 ✔
119
                        cacheKey,
120
                        () ->
121
                                findAllAndMakeThemAccessible(
1 ✔
122
                                        FieldCriteria.forEntireClassHierarchy().allThoseThatMatch(field -> {
1 ✔
123
                                                if (valueType == null) {
1 ✔
124
                                                        return field.getName().equals(fieldName);
1 ✔
125
                                                } else {
126
                                                        return field.getName().equals(fieldName) && Classes.INSTANCE.isAssignableFrom(field.getType(), valueType);
1 ✔
127
                                                }
128
                                        }), targetClass
129
                                )
130
                );
131
        }
132

133
        /**
134
         * Returns the first field with a given name in a class and in its hierarchy, made accessible. If there is no such
135
         * field, this method throws a {@link NoSuchFieldException}.
136
         *
137
         * @param targetClass the class
138
         * @param fieldName the name of the field
139
         * @return the field
140
         */
141
        public Field findFirstAndMakeItAccessible(Class<?> targetClass, String fieldName) {
142
                return findFirstAndMakeItAccessible(targetClass, fieldName, null);
×
143
        }
144

145
        /**
146
         * Returns the first field with a given name, whose type can hold a value of a given type, in a class and in its
147
         * hierarchy, made accessible. If there is no such field, this method throws a {@link NoSuchFieldException}.
148
         *
149
         * @param targetClass the class
150
         * @param fieldName the name of the field
151
         * @param fieldTypeOrSubType the type of the field or a subtype of it, or {@code null} for any type
152
         * @return the field
153
         */
154
        public Field findFirstAndMakeItAccessible(Class<?> targetClass, String fieldName, Class<?> fieldTypeOrSubType) {
155
                Collection<Field> members = findAllByExactNameAndMakeThemAccessible(targetClass, fieldName, fieldTypeOrSubType);
1 ✔
156
                if (members.size() < 1) {
1 ✔
157
                        Throwables.INSTANCE.throwException(
×
158
                                new NoSuchFieldException(
159
                                        Strings.INSTANCE.compile("Field {} not found in {} hierarchy", fieldName, targetClass.getName())
×
160
                                )
161
                        );
162
                }
163
                return members.stream().findFirst().get();
1 ✔
164
        }
165

166
        /**
167
         * Returns the only field with a given name in a class and in its hierarchy, made accessible. If there is no such
168
         * field, or there is more than one, this method throws a {@link NoSuchFieldException}.
169
         *
170
         * @param targetClass the class
171
         * @param memberName the name of the field
172
         * @return the field
173
         */
174
        public Field findOneAndMakeItAccessible(Class<?> targetClass, String memberName) {
175
                Collection<Field> members = findAllByExactNameAndMakeThemAccessible(targetClass, memberName, null);
1 ✔
176
                if (members.size() != 1) {
1 ✔
177
                        Throwables.INSTANCE.throwException(
×
178
                                new NoSuchFieldException(
179
                                                Strings.INSTANCE.compile("Field {} not found or found more than one field in {} hierarchy", memberName, targetClass.getName())
×
180
                                )
181
                        );
182
                }
183
                return members.stream().findFirst().get();
1 ✔
184
        }
185

186
        /**
187
         * Returns the value of a field of an object, read through {@link Facade#getFieldValue(Object, Field)}.
188
         *
189
         * @param <T> the type of the value
190
         * @param target the object, or {@code null} for a static field
191
         * @param field the field
192
         * @return the value of the field
193
         */
194
        public <T> T get(Object target, Field field) {
195
                return Facade.INSTANCE.getFieldValue(target, field);
1 ✔
196
        }
197

198
        /**
199
         * Returns the value of a field, found by name in the class of an object and in its hierarchy. If the field does not
200
         * exist, this method throws a {@link NoSuchFieldException}.
201
         *
202
         * @param <T> the type of the value
203
         * @param target the object
204
         * @param fieldName the name of the field
205
         * @return the value of the field
206
         */
207
        public <T> T get(Object target, String fieldName) {
208
                return get(target, findFirstAndMakeItAccessible(Classes.INSTANCE.retrieveFrom(target), fieldName, null));
1 ✔
209
        }
210

211
        /**
212
         * Returns the values of the fields of an object that match a criteria; the static fields are read without the
213
         * object.
214
         *
215
         * @param criteria the field criteria
216
         * @param target the object
217
         * @return the values, mapped by field
218
         */
219
        public Map<Field, ?> getAll(FieldCriteria criteria, Object target) {
220
                return getAll(() -> findAllAndMakeThemAccessible(criteria, Classes.INSTANCE.retrieveFrom(target)), target);
1 ✔
221
        }
222

223
        /**
224
         * Returns the values of all the fields of the class of an object and of its hierarchy, static fields included.
225
         *
226
         * @param target the object
227
         * @return the values, mapped by field
228
         */
229
        public Map<Field, ?> getAll(Object target) {
230
                return getAll(() -> findAllAndMakeThemAccessible(Classes.INSTANCE.retrieveFrom(target)), target);
1 ✔
231
        }
232

233
        /**
234
         * Returns the values of the fields of an object that match a criteria, all read with the object through
235
         * {@link Facade#getFieldValue(Object, Field)}.
236
         *
237
         * @param criteria the field criteria
238
         * @param target the object
239
         * @return the values, mapped by field
240
         */
241
        public Map<Field, ?> getAllDirect(FieldCriteria criteria, Object target) {
242
                return getAllDirect(() -> findAllAndMakeThemAccessible(criteria, Classes.INSTANCE.retrieveFrom(target)), target);
×
243
        }
244

245

246
        /**
247
         * Returns the values of all the fields of the class of an object and of its hierarchy, all read with the object
248
         * through {@link Facade#getFieldValue(Object, Field)}.
249
         *
250
         * @param target the object
251
         * @return the values, mapped by field
252
         */
253
        public Map<Field, ?> getAllDirect(Object target) {
254
                return getAllDirect(() -> findAllAndMakeThemAccessible(Classes.INSTANCE.retrieveFrom(target)), target);
1 ✔
255
        }
256

257
        /**
258
         * Returns the values of all the static fields of a class and of its hierarchy.
259
         *
260
         * @param targetClass the class
261
         * @return the values, mapped by field
262
         */
263
        public Map<Field, ?> getAllStatic(Class<?> targetClass) {
264
                return getAll(() -> findAllAndMakeThemAccessible(targetClass), null);
×
265
        }
266

267
        /**
268
         * Returns the values of all the fields of a class and of its hierarchy, read through
269
         * {@link Facade#getFieldValue(Object, Field)} without a target object: unlike {@link #getAllStatic(Class)}, it does
270
         * not skip the instance fields.
271
         *
272
         * @param targetClass the class
273
         * @return the values, mapped by field
274
         */
275
        public Map<Field, ?> getAllStaticDirect(Class<?> targetClass) {
276
                return getAllDirect(() -> findAllAndMakeThemAccessible(targetClass), null);
×
277
        }
278

279
        /**
280
         * Returns the value of a static field, found by name in a class and in its hierarchy. If the field does not exist,
281
         * this method throws a {@link NoSuchFieldException}.
282
         *
283
         * @param <T> the type of the value
284
         * @param targetClass the class
285
         * @param fieldName the name of the field
286
         * @return the value of the field
287
         */
288
        public <T> T getStatic(Class<?> targetClass, String fieldName) {
289
                return getStatic(findFirstAndMakeItAccessible(targetClass, fieldName, null));
×
290
        }
291

292
        /**
293
         * Returns the value of a static field.
294
         *
295
         * @param <T> the type of the value
296
         * @param field the static field
297
         * @return the value of the field
298
         */
299
        public <T> T getStatic(Field field) {
300
                return get(null, field);
×
301
        }
302

303
        /**
304
         * Sets the value of a field of an object through {@link Facade#setFieldValue(Object, Field, Object)}, which also
305
         * works on the final fields when the JVM driver is enabled.
306
         *
307
         * @param target the object, or {@code null} for a static field
308
         * @param field the field
309
         * @param value the value
310
         */
311
        public void set(Object target, Field field, Object value) {
312
                Facade.INSTANCE.setFieldValue(target, field, value);
1 ✔
313
        }
1 ✔
314

315
        /**
316
         * Sets the value of a field, found by name in the class of an object and in its hierarchy among the fields whose
317
         * type can hold the value. If the field does not exist, this method throws a {@link NoSuchFieldException}.
318
         *
319
         * @param target the object
320
         * @param fieldName the name of the field
321
         * @param value the value
322
         */
323
        public void set(Object target, String fieldName, Object value) {
324
                set(Classes.INSTANCE.retrieveFrom(target), target, fieldName, value);
1 ✔
325
        }
1 ✔
326

327
        /**
328
         * Sets the value of a static field, found by name in a class and in its hierarchy among the fields whose type can
329
         * hold the value. If the field does not exist, this method throws a {@link NoSuchFieldException}.
330
         *
331
         * @param targetClass the class
332
         * @param fieldName the name of the field
333
         * @param value the value
334
         */
335
        public void setStatic(Class<?> targetClass, String fieldName, Object value) {
336
                set(targetClass, null, fieldName, value);
×
337
        }
×
338

339
        /**
340
         * Sets the value of a static field.
341
         *
342
         * @param field the static field
343
         * @param value the value
344
         */
345
        public void setStatic(Field field, Object value) {
346
                set(null, field, value);
×
347
        }
×
348

349
        private Map<Field, Object> getAll(Supplier<Collection<Field>> fieldsSupplier, Object target) {
350
                Map<Field, Object> fieldValues = new HashMap<>();
1 ✔
351
                for (Field field : fieldsSupplier.get()) {
1 ✔
352
                        if (target != null) {
1 ✔
353
                                fieldValues.put(
1 ✔
354
                                        field,
355
                                        get(
1 ✔
356
                                                Modifier.isStatic(field.getModifiers()) ? null : target, field
1 ✔
357
                                        )
358
                                );
359
                        } else if (Modifier.isStatic(field.getModifiers())) {
×
360
                                fieldValues.put(
×
361
                                        field,
362
                                        get(null, field)
×
363
                                );
364
                        }
365
                }
1 ✔
366
                return fieldValues;
1 ✔
367
        }
368

369
        private Map<Field, ?> getAllDirect(Supplier<Collection<Field>> fieldsSupplier, Object target) {
370
                Map<Field, ?> fieldValues = new HashMap<>();
1 ✔
371
                for (Field field : fieldsSupplier.get()) {
1 ✔
372
                        fieldValues.put(
1 ✔
373
                                field,
374
                                Facade.INSTANCE.getFieldValue(target, field)
1 ✔
375
                        );
376
                }
1 ✔
377
                return fieldValues;
1 ✔
378
        }
379

380
        private void set(Class<?> targetClass, Object target, String fieldName, Object value) {
381
                set(target, findFirstAndMakeItAccessible(targetClass, fieldName, Classes.INSTANCE.retrieveFrom(value)), value);
1 ✔
382
        }
1 ✔
383

384
        /**
385
         * Thrown when a field is not found: unlike {@link java.lang.NoSuchFieldException}, it is unchecked.
386
         */
387
        public static class NoSuchFieldException extends RuntimeException {
388

389
                private static final long serialVersionUID = 3656790511956737635L;
390

391
                /**
392
                 * Creates the exception.
393
                 *
394
                 * @param message the detail message
395
                 */
396
                public NoSuchFieldException(String message) {
397
                        super(message);
×
398
                }
×
399

400
        }
401

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