• 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

88.03
/src/main/java/org/burningwave/reflection/FieldAccessor.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.Array;
33
import java.lang.reflect.Field;
34
import java.util.ArrayList;
35
import java.util.Collection;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Map;
39
import java.util.function.Supplier;
40
import java.util.regex.Matcher;
41
import java.util.regex.Pattern;
42

43
import org.burningwave.Throwables;
44
import org.burningwave.ThrowingBiFunction;
45
import org.burningwave.ThrowingFunction;
46

47

48
/**
49
 * Reads and writes the values of the fields of an object through a path, which can go through the fields of the fields
50
 * and through the elements of arrays, lists, maps and other collections:
51
 * <pre>{@code
52
 * String name = FieldAccessor.INSTANCE.get(order, "customer.name");
53
 * Object item = FieldAccessor.INSTANCE.get(order, "items[0]");
54
 * Object value = FieldAccessor.INSTANCE.get(object, "valuesByKey[key].values[2]");
55
 * FieldAccessor.INSTANCE.set(order, "customer.name", "John");
56
 * }</pre>
57
 * The segments of a path are separated by dots: each one is the name of a field, followed by any number of indexes in
58
 * brackets, or only indexes, which then apply to the object reached so far. An index is the position of an element in
59
 * an array, in a list or, in the order of its iterator, in another collection, or the key of an element in a map whose
60
 * keys are strings. The fields are read and written through {@link Fields}.
61
 */
62
@SuppressWarnings("unchecked")
63
public abstract class FieldAccessor {
64

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

70
        private final static String REG_EXP_FOR_INDEXES_OF_INDEXED_FIELDS = "\\[(.*?)\\]";
71
        private final static String REG_EXP_FOR_SIMPLE_FIELDS = "([a-zA-Z\\$\\_\\-0-9]*)(\\[*.*)";
72

73
        static {
74
                INSTANCE = new ByFieldOrByMethod();
1 ✔
75
        }
1 ✔
76
        private List<ThrowingBiFunction<Object, String, Object, Throwable>> fieldRetrievers;
77
        private List<ThrowingFunction<Object[], Boolean, Throwable>> fieldSetters;
78
        private Pattern indexesSearcherForIndexedField;
79

80
        private Pattern simpleFieldSearcher;
81

82
        FieldAccessor() {
1 ✔
83
                this.fieldRetrievers = getFieldRetrievers();
1 ✔
84
                this.fieldSetters= getFieldSetters();
1 ✔
85
                this.simpleFieldSearcher = Pattern.compile(REG_EXP_FOR_SIMPLE_FIELDS);
1 ✔
86
                this.indexesSearcherForIndexedField = Pattern.compile(REG_EXP_FOR_INDEXES_OF_INDEXED_FIELDS);
1 ✔
87
        }
1 ✔
88

89
        /**
90
         * Returns the value at the end of a path that starts from an object. If the path is {@code null}, this method
91
         * throws an {@link IllegalArgumentException}.
92
         *
93
         * @param <T> the type of the value
94
         * @param obj the object
95
         * @param path the path
96
         * @return the value
97
         */
98
        public <T> T get(Object obj, String path) {
99
                if (path == null) {
1 ✔
100
                        throw new IllegalArgumentException("Field path cannot be null");
×
101
                }
102
                String[] pathSegments = path.split("\\.");
1 ✔
103
                Object objToReturn = obj;
1 ✔
104
                for (int j = 0; j < pathSegments.length; j++) {
1 ✔
105
                        objToReturn = getField(j != 0 ? objToReturn : obj, pathSegments[j]);
1 ✔
106
                }
107
                return (T)objToReturn;
1 ✔
108
        }
109

110
        /**
111
         * Sets the value at the end of a path that starts from an object: the object reached by the path without its last
112
         * segment is read as {@link #get(Object, String)} does, then the last segment is written. An empty path is ignored
113
         * and, if the path is {@code null}, this method throws an {@link IllegalArgumentException}.
114
         *
115
         * @param obj the object
116
         * @param path the path
117
         * @param value the value
118
         */
119
        public void set(Object obj, String path, Object value) {
120
                if (path == null) {
1 ✔
121
                        throw new IllegalArgumentException("Field path cannot be null");
×
122
                }
123
                if (path.trim().isEmpty()) {
1 ✔
124
                        return;
×
125
                }
126
                Object target =
1 ✔
127
                                path.contains(".")?
1 ✔
128
                                                get(obj, path.substring(0, path.lastIndexOf("."))) :
1 ✔
129
                                                        obj;
130
                String targetPathSegment =
1 ✔
131
                                path.contains(".")?
1 ✔
132
                                                path.substring(path.lastIndexOf(".") + 1, path.length()) :
1 ✔
133
                                                        path;
134
                setField(target, targetPathSegment, value);
1 ✔
135
        }
1 ✔
136

137
        abstract List<ThrowingBiFunction<Object, String, Object, Throwable>> getFieldRetrievers();
138

139
        abstract List<ThrowingFunction<Object[], Boolean, Throwable>> getFieldSetters();
140

141
        Object retrieveFieldByDirectAccess(Object target, String pathSegment) throws IllegalAccessException {
142
                if (pathSegment.trim().isEmpty()) {
1 ✔
143
                        return target;
1 ✔
144
                }
145
                return Fields.INSTANCE.get(target, pathSegment);
1 ✔
146
        }
147

148
        Boolean setFieldByDirectAccess(Object target, String pathSegment, Object value) throws IllegalAccessException {
149
                Matcher matcher = simpleFieldSearcher.matcher(pathSegment);
1 ✔
150
                matcher.find();
1 ✔
151
                if (matcher.group(2).isEmpty()) {
1 ✔
152
                        Field field = Fields.INSTANCE.findOneAndMakeItAccessible(target.getClass(), matcher.group(1));
1 ✔
153
                        Fields.INSTANCE.set(target, field, value);
1 ✔
154
                } else {
1 ✔
155
                        if (target.getClass().isArray() || target instanceof Map || target instanceof Collection) {
1 ✔
156
                                setInIndexedField(target, matcher.group(2), value);
1 ✔
157
                        } else {
158
                                Field field = Fields.INSTANCE.findOneAndMakeItAccessible(target.getClass(), matcher.group(1));
1 ✔
159
                                setInIndexedField(field.get(target), matcher.group(2), value);
1 ✔
160
                        }
161
                }
162
                return Boolean.TRUE;
1 ✔
163
        }
164

165

166
        private <T> int convertAndCheckIndex(Collection<T> collection, String indexAsString) {
167
                int index = Integer.valueOf(indexAsString);
1 ✔
168
                if (collection.size() < index) {
1 ✔
169
                        throw new IndexOutOfBoundsException(("Illegal index "+ indexAsString +", collection size " + collection.size()));
×
170
                }
171
                return index;
1 ✔
172
        }
173

174
        private Object getField(Object obj, String pathSegment) {
175
                Object objToReturn = null;
1 ✔
176
                Matcher matcher = simpleFieldSearcher.matcher(pathSegment);
1 ✔
177
                matcher.find();
1 ✔
178
                List<Throwable> exceptions = new ArrayList<>();
1 ✔
179
                for (ThrowingBiFunction<Object, String, Object, Throwable> retriever : fieldRetrievers) {
1 ✔
180
                        try {
181
                                if ((objToReturn = retriever.apply(obj, matcher.group(1))) != null) {
1 ✔
182
                                        break;
1 ✔
183
                                }
184
                        } catch (Throwable exc) {
×
185
                                exceptions.add(exc);
×
186
                        }
×
187
                }
×
188
                manageGetFieldExceptions(exceptions);
1 ✔
189
                if (!matcher.group(2).isEmpty()) {
1 ✔
190
                        try {
191
                                objToReturn = retrieveFromIndexedField(objToReturn, matcher.group(2));
1 ✔
192
                        } catch (Throwable exc) {
×
193
                                exceptions.add(exc);
×
194
                        }
1 ✔
195
                }
196
                return objToReturn;
1 ✔
197
        }
198

199
        private void manageGetFieldExceptions(List<Throwable> exceptions) {
200
                if (exceptions.size() == fieldRetrievers.size()) {
1 ✔
201
                        Throwables.INSTANCE.throwException(exceptions.iterator().next());
×
202
                }
203
        }
1 ✔
204

205
        private <T> Object retrieveFromIndexedField(Object fieldValue, String indexes) {
206
                Matcher matcher = indexesSearcherForIndexedField.matcher(indexes);
1 ✔
207
                if (matcher.find()) {
1 ✔
208
                        String index = matcher.group(1);
1 ✔
209
                        Supplier<Object> propertyRetriever = null;
1 ✔
210
                        if (fieldValue.getClass().isArray()) {
1 ✔
211
                                propertyRetriever = () -> Array.get(fieldValue, Integer.valueOf(index));
1 ✔
212
                        } else if (fieldValue instanceof List) {
1 ✔
213
                                propertyRetriever = () -> ((List<?>)fieldValue).get(Integer.valueOf(index));
1 ✔
214
                        } else if (fieldValue instanceof Map) {
1 ✔
215
                                propertyRetriever = () -> ((Map<?, ?>)fieldValue).get(index);
1 ✔
216
                        } else if (fieldValue instanceof Collection) {
1 ✔
217
                                propertyRetriever = () -> {
1 ✔
218
                                        Collection<T> collection = (Collection<T>)fieldValue;
1 ✔
219
                                        int indexAsInt = convertAndCheckIndex(collection, index);
1 ✔
220
                                        Iterator<T> itr = collection.iterator();
1 ✔
221
                                        int currentIterationIndex = 0;
1 ✔
222
                                        while (itr.hasNext()) {
1 ✔
223
                                                Object currentIteartedObject = itr.next();
1 ✔
224
                                                if (currentIterationIndex++ == indexAsInt) {
1 ✔
225
                                                        return currentIteartedObject;
1 ✔
226
                                                }
227
                                        }
1 ✔
228
                                        return null;
×
229
                                };
230
                        } else {
231
                                return Throwables.INSTANCE.throwException("indexed property {} of type {} is not supporterd", fieldValue, fieldValue.getClass());
×
232
                        }
233
                        return retrieveFromIndexedField(
1 ✔
234
                                propertyRetriever.get(),
1 ✔
235
                                indexes.substring(matcher.end(), indexes.length())
1 ✔
236
                        );
237
                }
238
                return fieldValue;
1 ✔
239
        }
240

241
        private void setField(Object target, String pathSegment, Object value) {
242
                List<Throwable> exceptions = new ArrayList<>();
1 ✔
243
                for (ThrowingFunction<Object[], Boolean, Throwable> setter : fieldSetters) {
1 ✔
244
                        try {
245
                                setter.apply(new Object[] {target, pathSegment, value});
1 ✔
246
                                break;
1 ✔
247
                        } catch (Throwable exc) {
×
248
                                exceptions.add(exc);
×
249
                        }
250
                }
×
251
                manageGetFieldExceptions(exceptions);
1 ✔
252
        }
1 ✔
253

254
        private <T> void setIndexedValue(Collection<T> collection, String index, Object value) {
255
                int indexAsInt = convertAndCheckIndex(collection, index);
1 ✔
256
                List<T> tempList = new ArrayList<>();
1 ✔
257
                Iterator<T> itr = collection.iterator();
1 ✔
258
                while (itr.hasNext()) {
1 ✔
259
                        tempList.add(itr.next());
1 ✔
260
                }
261
                int iterationIndex = 0;
1 ✔
262
                collection.clear();
1 ✔
263
                itr = tempList.iterator();
1 ✔
264
                while (itr.hasNext()) {
1 ✔
265
                        T origVal = itr.next();
1 ✔
266
                        if (iterationIndex++ != indexAsInt) {
1 ✔
267
                                collection.add(origVal);
1 ✔
268
                        } else {
269
                                collection.add((T)value);
1 ✔
270
                        }
271
                }
1 ✔
272
        }
1 ✔
273

274
        private <T> void setInIndexedField(Object fieldValue, String indexes, Object value) {
275
                Matcher matcher = indexesSearcherForIndexedField.matcher(indexes);
1 ✔
276
                int lastIndexOf = 0;
1 ✔
277
                String index = null;
1 ✔
278
                while (matcher.find()) {
1 ✔
279
                        index = matcher.group(1);
1 ✔
280
                        lastIndexOf = matcher.start();
1 ✔
281
                }
282
                Object targetObject = retrieveFromIndexedField(fieldValue, indexes.substring(0, lastIndexOf));
1 ✔
283
                if (targetObject.getClass().isArray()) {
1 ✔
284
                        Array.set(targetObject, Integer.valueOf(index), value);
1 ✔
285
                } else if (targetObject instanceof List) {
1 ✔
286
                        ((List<T>)targetObject).set(Integer.valueOf(index), (T)value);
1 ✔
287
                } else if (targetObject instanceof Map) {
1 ✔
288
                        ((Map<String, T>)targetObject).put(index, (T)value);
1 ✔
289
                } else if (targetObject instanceof Collection) {
1 ✔
290
                        setIndexedValue((Collection<T>) targetObject, index, value);
1 ✔
291
                } else {
292
                        Throwables.INSTANCE.throwException("indexed property {} of type {} is not supporterd", fieldValue, fieldValue.getClass());
×
293
                }
294
        }
1 ✔
295

296
        private static class ByFieldOrByMethod extends FieldAccessor {
297

298
                private ByFieldOrByMethod() {
299
                        super();
1 ✔
300
                }
1 ✔
301

302
                @Override
303
                List<ThrowingBiFunction<Object, String, Object, Throwable>> getFieldRetrievers() {
304
                        List<ThrowingBiFunction<Object, String, Object, Throwable>> retrievers = new ArrayList<>();
1 ✔
305
                        retrievers.add((object, pathSegment) -> retrieveFieldByDirectAccess(object, pathSegment));
1 ✔
306
                        return retrievers;
1 ✔
307
                }
308

309
                @Override
310
                List<ThrowingFunction<Object[], Boolean, Throwable>> getFieldSetters() {
311
                        List<ThrowingFunction<Object[], Boolean, Throwable>> setters  = new ArrayList<>();
1 ✔
312
                        setters.add(objects -> setFieldByDirectAccess(objects[0], (String)objects[1], objects[2]));
1 ✔
313
                        return setters;
1 ✔
314
                }
315
        }
316

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