From e79d7801f0ba4859717cdb51ecfdc40ae95fc9a9 Mon Sep 17 00:00:00 2001 From: raduking Date: Thu, 19 Nov 2026 17:41:04 +0200 Subject: [PATCH 01/20] Release `v1.1.2`. --- CHANGELOG.md | 4 ++++ README.md | 4 ++-- pom.xml | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3de9619c..f0e43326 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Release Notes +`1.1.2` + +--- + `1.1.1` - Kept `Fields.IgnoreAccess.get(Object, String)` throwing `ReflectionException` for null input while using unchecked lookup for valid input. diff --git a/README.md b/README.md index 56475b57..fd69d313 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ A library that exposes general Java utility and reflection methods and a package ### Releases -Current release `1.1.1` +Current release `1.1.2` ### Documentation @@ -81,6 +81,6 @@ Maven: add this dependency to your `pom.xml` io.github.raduking morphix-all - 1.1.1 + 1.1.2 ``` diff --git a/pom.xml b/pom.xml index 4928ccc3..08cdd4ba 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ io.github.raduking morphix-all - 1.1.1 + 1.1.2 jar ${project.groupId}:${project.artifactId} From 142c20233fa0126f1af075cff10e599fe231db31 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 01:23:45 +0200 Subject: [PATCH 02/20] JSON like syntax for field finder - part 1. --- CHANGELOG.md | 4 + .../convert/strategy/FinderPathStrategy.java | 60 ++- .../org/morphix/reflection/FieldPaths.java | 352 ++++++++++++++++++ .../java/org/morphix/reflection/Fields.java | 45 +-- .../morphix/reflection/FieldPathsTest.java | 131 +++++++ .../reflection/FieldsSafeGetByPathTest.java | 57 +++ .../reflection/FieldsSafeGetByPathsTest.java | 21 ++ 7 files changed, 621 insertions(+), 49 deletions(-) create mode 100644 src/main/java/org/morphix/reflection/FieldPaths.java create mode 100644 src/test/java/org/morphix/reflection/FieldPathsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index f0e43326..5d3726ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ `1.1.2` +- Added `FieldPaths` for JSON Path-style field path parsing and resolution (properties, indices, and map keys). +- Changed `Fields.Safe.getByPath` to resolve JSON Path-style expressions including array, list, and map selectors. +- Changed `Fields.Safe.getByPaths(Object, String)` to split alternate paths on commas outside bracket segments. + --- `1.1.1` diff --git a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 2c7b428f..7ba48249 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -17,8 +17,14 @@ import java.lang.reflect.Field; import java.util.List; +import java.util.Map; +import org.morphix.lang.collections.Lists; +import org.morphix.reflection.Classes; import org.morphix.reflection.ExtendedField; +import org.morphix.reflection.FieldPaths; +import org.morphix.reflection.FieldPaths.Step; +import org.morphix.reflection.FieldPaths.StepKind; import org.morphix.reflection.Fields; /** @@ -53,30 +59,48 @@ public ExtendedField find(final T source, final List fields, * @return field object pair */ public static ExtendedField getConverterFieldByPathInHierarchy(final T obj, final String path) { - String[] fieldNames = path.split("\\."); - + List steps = FieldPaths.parse(path); + if (Lists.isEmpty(steps)) { + return ExtendedField.EMPTY; + } Field resultField = null; Object resultObject = obj; Class currentClass = resultObject.getClass(); - - for (String fieldName : fieldNames) { - if (null != resultField && null != resultObject) { - resultObject = Fields.IgnoreAccess.get(resultObject, resultField); - } - resultField = Fields.getOneDeclaredInHierarchy(currentClass, fieldName); - if (null != resultField && STATIC.isPresentOn(resultField)) { - resultField = null; - } - if (null != resultField) { - currentClass = resultField.getType(); + for (Step step : steps) { + if (StepKind.PROPERTY == step.kind()) { + if (null != resultField && null != resultObject) { + resultObject = Fields.IgnoreAccess.get(resultObject, resultField); + } + if (null == resultObject) { + return ExtendedField.EMPTY; + } + currentClass = Classes.getFrom(resultObject); + resultField = Fields.getOneDeclaredInHierarchy(currentClass, step.selector()); + if (null != resultField && STATIC.isPresentOn(resultField)) { + return ExtendedField.EMPTY; + } + if (null == resultField && resultObject instanceof Map map) { + if (!map.containsKey(step.selector())) { + return ExtendedField.EMPTY; + } + resultObject = map.get(step.selector()); + continue; + } + if (null == resultField) { + return ExtendedField.EMPTY; + } } else { - resultObject = null; - } - if (null == resultField) { - break; + if (null != resultField && null != resultObject) { + resultObject = Fields.IgnoreAccess.get(resultObject, resultField); + } + resultObject = FieldPaths.navigate(resultObject, step); + resultField = null; + if (null == resultObject) { + return ExtendedField.EMPTY; + } } } - if (null == resultObject) { + if (null == resultObject || null == resultField) { return ExtendedField.EMPTY; } return of(resultField, resultObject); diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java new file mode 100644 index 00000000..5c76742c --- /dev/null +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -0,0 +1,352 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.reflection; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.morphix.lang.JavaObjects; +import org.morphix.lang.collections.Lists; + +/** + * Parses and resolves JSON Path-style selectors for field and container access (properties, array or list indices, and + * map keys). + * + * @author Radu Sebastian LAZIN + */ +public interface FieldPaths { + + /** + * Kind of path step. + */ + enum StepKind { + + /** + * A property or map key accessed with dot notation. + */ + PROPERTY, + + /** + * A zero-based index into an array or list. + */ + INDEX, + + /** + * A map key from bracket notation. + */ + KEY + } + + /** + * One step in a path expression. + * + * @param kind step kind + * @param selector property name, index text, or map key + */ + record Step(StepKind kind, String selector) { + // empty + } + + /** + * Resolves the value at the given path starting from {@code root}, using the same rules as + * {@link Fields.Safe#getByPath(Object, String)}. + * + * @param value type + * + * @param root start object + * @param path path expression + * @return value at the path, or {@code null} if the path is empty, invalid, or not found + */ + static U resolveValue(final Object root, final String path) { + List steps = parse(path); + if (Lists.isEmpty(steps)) { + return null; + } + Object current = root; + for (Step step : steps) { + current = navigate(current, step); + if (null == current) { + break; + } + } + return JavaObjects.cast(current); + } + + /** + * Parses a path into steps. Returns an empty list for an empty path, or {@code null} when the expression is invalid. + * + * @param path path expression + * @return parsed steps, empty list for {@code ""}, or {@code null} if invalid + */ + static List parse(final String path) { + if (path.isEmpty()) { + return List.of(); + } + List steps = new ArrayList<>(); + int index = 0; + int length = path.length(); + while (index < length) { + if (path.charAt(index) == '.') { + return null; + } + int propertyStart = index; + while (index < length) { + char ch = path.charAt(index); + if (ch == '.' || ch == '[') { + break; + } + index++; + } + if (propertyStart < index) { + steps.add(new Step(StepKind.PROPERTY, path.substring(propertyStart, index))); + } + index = parseBracketSteps(path, index, length, steps); + if (index < 0) { + return null; + } + if (index < length) { + if (path.charAt(index) != '.') { + return null; + } + index++; + if (index >= length) { + steps.add(new Step(StepKind.PROPERTY, "")); + return steps; + } + } + } + return steps; + } + + /** + * Splits a comma-separated list of paths, ignoring commas inside {@code [...]} segments. + * + * @param paths comma-separated path expressions + * @return trimmed non-empty paths, or an empty list when nothing remains after trimming + */ + static List split(final String paths) { + if (paths.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int bracketDepth = 0; + boolean inSingleQuote = false; + boolean inDoubleQuote = false; + for (int i = 0; i < paths.length(); ++i) { + char ch = paths.charAt(i); + if (inSingleQuote) { + current.append(ch); + if (ch == '\'' && (i == 0 || paths.charAt(i - 1) != '\\')) { + inSingleQuote = false; + } + continue; + } + if (inDoubleQuote) { + current.append(ch); + if (ch == '"' && (i == 0 || paths.charAt(i - 1) != '\\')) { + inDoubleQuote = false; + } + continue; + } + if (ch == '\'') { + inSingleQuote = true; + current.append(ch); + continue; + } + if (ch == '"') { + inDoubleQuote = true; + current.append(ch); + continue; + } + if (ch == '[') { + bracketDepth++; + current.append(ch); + continue; + } + if (ch == ']') { + bracketDepth--; + current.append(ch); + continue; + } + if (ch == ',' && bracketDepth == 0) { + String path = current.toString().trim(); + if (!path.isEmpty()) { + result.add(path); + } + current.setLength(0); + continue; + } + current.append(ch); + } + String path = current.toString().trim(); + if (!path.isEmpty()) { + result.add(path); + } + return result; + } + + /** + * Applies a single step to the current value. + * + * @param current current value + * @param step step to apply + * @return next value, or {@code null} if navigation fails + */ + static Object navigate(final Object current, final Step step) { + return switch (step.kind()) { + case PROPERTY -> readProperty(current, step.selector()); + case INDEX -> readIndex(current, step.selector()); + case KEY -> readMapKey(current, step.selector()); + }; + } + + /** + * @see StepKind#PROPERTY + */ + static Object readProperty(final Object current, final String propertyName) { + if (null == current || null == propertyName || propertyName.isEmpty()) { + return null; + } + Class cls = Classes.getFrom(current); + Field field = Fields.Unchecked.getOneDeclaredInHierarchy(cls, propertyName); + if (null != field) { + return Fields.Safe.get(current, field); + } + if (current instanceof Map map) { + return map.get(propertyName); + } + return null; + } + + /** + * @see StepKind#INDEX + */ + static Object readIndex(final Object current, final String indexText) { + if (null == current || null == indexText) { + return null; + } + int index; + try { + index = Integer.parseInt(indexText); + } catch (NumberFormatException e) { + return null; + } + if (index < 0) { + return null; + } + if (current instanceof List list) { + return index < list.size() ? list.get(index) : null; + } + if (current.getClass().isArray()) { + int length = Array.getLength(current); + return index < length ? Array.get(current, index) : null; + } + return null; + } + + /** + * @see StepKind#KEY + */ + static Object readMapKey(final Object current, final String key) { + if (null == current || null == key) { + return null; + } + if (current instanceof Map map) { + return map.get(key); + } + return null; + } + + private static int parseBracketSteps(final String path, final int index, final int length, final List steps) { + int currentIndex = index; + while (currentIndex < length && path.charAt(currentIndex) == '[') { + ++currentIndex; + if (currentIndex >= length) { + return -1; + } + char ch = path.charAt(currentIndex); + if (ch == '\'' || ch == '"') { + int[] nextIndex = new int[1]; + String key = readQuoted(path, currentIndex, length, ch, nextIndex); + if (null == key) { + return -1; + } + steps.add(new Step(StepKind.KEY, key)); + currentIndex = nextIndex[0]; + } else { + int selectorStart = index; + while (currentIndex < length && path.charAt(currentIndex) != ']') { + ++currentIndex; + } + if (currentIndex >= length) { + return -1; + } + String selector = path.substring(selectorStart, currentIndex); + if (selector.isEmpty()) { + return -1; + } + if (isInteger(selector)) { + steps.add(new Step(StepKind.INDEX, selector)); + } else { + steps.add(new Step(StepKind.KEY, selector)); + } + } + if (currentIndex >= length || path.charAt(currentIndex) != ']') { + return -1; + } + ++currentIndex; + } + return currentIndex; + } + + private static boolean isInteger(final String text) { + if (text.isEmpty()) { + return false; + } + for (int i = 0; i < text.length(); ++i) { + if (!Character.isDigit(text.charAt(i))) { + return false; + } + } + return true; + } + + private static String readQuoted(final String path, final int start, final int length, final char quote, final int[] nextIndexOut) { + StringBuilder builder = new StringBuilder(); + int index = start + 1; + while (index < length) { + char ch = path.charAt(index); + if (ch == '\\') { + ++index; + if (index >= length) { + return null; + } + builder.append(path.charAt(index)); + index++; + continue; + } + if (ch == quote) { + ++index; + nextIndexOut[0] = index; + return builder.toString(); + } + builder.append(ch); + ++index; + } + return null; + } +} diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index a0d4af60..e27cf26e 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -13,7 +13,6 @@ package org.morphix.reflection; import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; @@ -799,8 +798,7 @@ static T getStatic(final Field field) { } /** - * Returns the field value for the given object. Field is searched with the field path.
- * TODO: implement full functionality similar to JSON Path + * Returns the field value for the given object. Field is searched with the field path. * * @param object type * @param field value type @@ -840,14 +838,7 @@ static U getByPaths(final T obj, final String paths) { if (paths.isEmpty()) { return null; } - String[] parts = paths.split(",", -1); - List trimmedPaths = new ArrayList<>(parts.length); - for (String part : parts) { - String path = part.trim(); - if (!path.isEmpty()) { - trimmedPaths.add(path); - } - } + List trimmedPaths = FieldPaths.split(paths); if (trimmedPaths.isEmpty()) { return null; } @@ -855,36 +846,28 @@ static U getByPaths(final T obj, final String paths) { } /** - * Returns the field value given by its qualified path to the required field in the given object. The field is read - * directly, without going through a getter method. + * Returns the field value given by its path to the required field in the given object. The field is read directly, + * without going through a getter method. + *

+ * Paths use dot notation for properties (for example {@code inner.value}), bracket notation for array or list indices + * (for example {@code items[0].name}), and quoted or unquoted map keys (for example {@code data['key']} or + * {@code data[key]}). When a property is not declared on an object, a {@link java.util.Map} value is consulted. * * @param object type * @param field value type * * @param obj object to get the field from - * @param path qualified path to the field - * @return field value or null if the field is not found or if the object is null + * @param path path to the value + * @return field or container value, or {@code null} if the path is empty, invalid, not found, or {@code obj} is + * {@code null} * @throws ReflectionException if {@code path} is null */ static U getByPath(final T obj, final String path) { Reflection.requireNotNull(path, "Cannot resolve field path: path is null"); - U result = null; - String[] fieldNames = path.split("\\.", -1); - if (fieldNames.length == 1) { - result = Safe.get(obj, fieldNames[0]); - } else { - Object value = obj; - for (String fieldName : fieldNames) { - value = Safe.get(value, fieldName); - if (null == value) { - break; - } - } - if (null != value) { - result = JavaObjects.cast(value); - } + if (null == obj) { + return null; } - return result; + return FieldPaths.resolveValue(obj, path); } } diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java new file mode 100644 index 00000000..6a8269a3 --- /dev/null +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.reflection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.morphix.lang.collections.FastArrayList; + +/** + * Test class for {@link FieldPaths}. + * + * @author Radu Sebastian LAZIN + */ +class FieldPathsTest { + + public static class Entry { + + public String name; + } + + public static class WithContainers { + + public Entry[] entries = { new Entry() }; + + public List items = new FastArrayList<>(new Entry[] { new Entry() }); + + public Map data = new LinkedHashMap<>(); + + public WithContainers() { + entries[0].name = "fromArray"; + items.get(0).name = "fromList"; + data.put("key", "fromMap"); + data.put("a,b", "commaKey"); + } + } + + @Test + void shouldParseDotSeparatedProperties() { + List steps = FieldPaths.parse("inner.value"); + + assertThat(steps.size(), equalTo(2)); + assertThat(steps.get(0).kind(), equalTo(FieldPaths.StepKind.PROPERTY)); + assertThat(steps.get(0).selector(), equalTo("inner")); + assertThat(steps.get(1).selector(), equalTo("value")); + } + + @Test + void shouldParseArrayIndexAndProperty() { + List steps = FieldPaths.parse("entries[0].name"); + + assertThat(steps.size(), equalTo(3)); + assertThat(steps.get(1).kind(), equalTo(FieldPaths.StepKind.INDEX)); + assertThat(steps.get(1).selector(), equalTo("0")); + assertThat(steps.get(2).selector(), equalTo("name")); + } + + @Test + void shouldReturnNullForInvalidExpression() { + assertThat(FieldPaths.parse(".inner"), nullValue()); + assertThat(FieldPaths.parse("entries[0"), nullValue()); + assertThat(FieldPaths.parse("entries[]"), nullValue()); + } + + @Test + void shouldSplitCommaSeparatedPathsOutsideBrackets() { + List paths = FieldPaths.split("entries[0].name,data['a,b'],items[1].name"); + + assertThat(paths.size(), equalTo(3)); + assertThat(paths.get(0), equalTo("entries[0].name")); + assertThat(paths.get(1), equalTo("data['a,b']")); + assertThat(paths.get(2), equalTo("items[1].name")); + } + + @Test + void shouldResolveArrayListAndMapPaths() { + WithContainers root = new WithContainers(); + + assertThat(FieldPaths.resolveValue(root, "entries[0].name"), equalTo("fromArray")); + assertThat(FieldPaths.resolveValue(root, "items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValue(root, "data['key']"), equalTo("fromMap")); + assertThat(FieldPaths.resolveValue(root, "data['a,b']"), equalTo("commaKey")); + assertThat(FieldPaths.resolveValue(root, "data[key]"), equalTo("fromMap")); + assertThat(FieldPaths.resolveValue(root, "items[9].name"), nullValue()); + } + + @Test + void shouldReturnNullForEmptyOrInvalidResolve() { + WithContainers root = new WithContainers(); + + assertThat(FieldPaths.resolveValue(root, ""), nullValue()); + assertThat(FieldPaths.resolveValue(root, ".bad"), nullValue()); + assertThat(FieldPaths.resolveValue(root, "entries[-1]"), nullValue()); + assertThat(FieldPaths.resolveValue(null, "entries[0]"), nullValue()); + assertThat(FieldPaths.resolveValue(root, "entries[notAnIndex]"), nullValue()); + assertThat(FieldPaths.resolveValue(root, "items[0]"), equalTo(root.items.get(0))); + } + + @Test + void shouldUnescapeQuotedMapKeys() { + WithContainers root = new WithContainers(); + root.data.put("say \"hi\"", "quoted"); + + assertThat(FieldPaths.resolveValue(root, "data['say \\\"hi\\\"']"), equalTo("quoted")); + } + + @Test + void shouldResolveNestedArrayIndices() { + WithContainers root = new WithContainers(); + root.entries = new Entry[] { new Entry(), new Entry() }; + root.entries[1].name = "second"; + + assertThat(FieldPaths.resolveValue(root, "entries[1].name"), equalTo("second")); + } +} diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 44fa7824..989e6830 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -17,7 +17,12 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.Test; +import org.morphix.lang.collections.FastArrayList; /** * Test class for {@link Fields.Safe#getByPath(Object, String)}. @@ -46,6 +51,20 @@ public static class WithNestedField { public WithTransformingGetter inner = new WithTransformingGetter(); } + public static class WithIndexedContainers { + + public String[] tags = { "alpha", "beta" }; + + public List codes = new FastArrayList<>(new String[] { "x", "y" }); + + public Map attributes = new LinkedHashMap<>(); + + public WithIndexedContainers() { + attributes.put("color", "blue"); + attributes.put("size", "large"); + } + } + @Test void shouldGetFieldAtFirstLevel() { WithNestedField obj = new WithNestedField(); @@ -127,4 +146,42 @@ void shouldThrowWhenPathIsNull() { ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPath(new WithNestedField(), null)); assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null")); } + + @Test + void shouldGetValueByArrayIndexPath() { + WithIndexedContainers obj = new WithIndexedContainers(); + + assertThat(Fields.Safe.getByPath(obj, "tags[1]"), equalTo("beta")); + assertThat(Fields.Safe.getByPath(obj, "tags[0]"), equalTo("alpha")); + } + + @Test + void shouldGetValueByListIndexPath() { + WithIndexedContainers obj = new WithIndexedContainers(); + + assertThat(Fields.Safe.getByPath(obj, "codes[1]"), equalTo("y")); + } + + @Test + void shouldGetValueByMapKeyPath() { + WithIndexedContainers obj = new WithIndexedContainers(); + + assertThat(Fields.Safe.getByPath(obj, "attributes['color']"), equalTo("blue")); + assertThat(Fields.Safe.getByPath(obj, "attributes[size]"), equalTo("large")); + } + + @Test + void shouldGetNestedValueAfterIndexPath() { + WithIndexedContainers obj = new WithIndexedContainers(); + obj.tags = new String[] { "outer" }; + Wrapper wrapper = new Wrapper(); + wrapper.row = obj; + + assertThat(Fields.Safe.getByPath(wrapper, "row.tags[0]"), equalTo("outer")); + } + + public static class Wrapper { + + public WithIndexedContainers row; + } } diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 895219fc..2b4bde62 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -17,6 +17,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.LinkedHashMap; +import java.util.Map; + import org.junit.jupiter.api.Test; /** @@ -33,7 +36,10 @@ public static class A { } public static class B { + public A a; + + public Map keyed = new LinkedHashMap<>(); } @Test @@ -143,4 +149,19 @@ void shouldThrowWhenPathsArrayIsNull() { assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null")); } + @Test + void shouldNotSplitOnCommaInsideBrackets() { + A fromMap = new A(); + fromMap.x = "commaKey"; + A fromDot = new A(); + fromDot.x = "dotPath"; + B b = new B(); + b.keyed.put("a,b", fromMap); + b.a = fromDot; + + String value = Fields.Safe.getByPaths(b, "keyed['a,b'].x,a.x"); + + assertThat(value, equalTo("commaKey")); + } + } From f392ea0ed6e82501d213edc35f34a296f3f04201 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 01:33:10 +0200 Subject: [PATCH 03/20] Added JUnit6 to Eclipse classpath. --- .classpath | 1 + 1 file changed, 1 insertion(+) diff --git a/.classpath b/.classpath index dd3c948b..59b1c7f8 100644 --- a/.classpath +++ b/.classpath @@ -36,5 +36,6 @@ + From eb954ad1a6f4a2f4bccdead8a9d7434199083ac3 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 01:35:56 +0200 Subject: [PATCH 04/20] Share cursor-based field path parser and support comma-separated alternatives --- .../convert/strategy/FinderPathStrategy.java | 60 +--- .../morphix/reflection/FieldPathParser.java | 294 +++++++++++++++ .../org/morphix/reflection/FieldPaths.java | 335 +++--------------- .../java/org/morphix/reflection/Fields.java | 13 +- .../convert/annotation/DeepSourceTest.java | 35 ++ .../strategy/FinderPathStrategyTest.java | 116 ++++++ .../morphix/reflection/FieldPathsTest.java | 77 ++-- .../reflection/FieldsSafeGetByPathsTest.java | 17 + 8 files changed, 577 insertions(+), 370 deletions(-) create mode 100644 src/main/java/org/morphix/reflection/FieldPathParser.java create mode 100644 src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java diff --git a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 7ba48249..13fa1792 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -12,20 +12,10 @@ */ package org.morphix.convert.strategy; -import static org.morphix.reflection.ExtendedField.of; -import static org.morphix.reflection.JavaModifier.STATIC; - -import java.lang.reflect.Field; import java.util.List; -import java.util.Map; -import org.morphix.lang.collections.Lists; -import org.morphix.reflection.Classes; import org.morphix.reflection.ExtendedField; import org.morphix.reflection.FieldPaths; -import org.morphix.reflection.FieldPaths.Step; -import org.morphix.reflection.FieldPaths.StepKind; -import org.morphix.reflection.Fields; /** * Finds the field in the source by path. @@ -50,59 +40,15 @@ public ExtendedField find(final T source, final List fields, } /** - * Returns the field and the object it corresponds to given its path. + * Returns the first field and its owning object from comma-separated alternative paths. * * @param object type * * @param obj object on which to search - * @param path path to the wanted field (object) + * @param path alternative paths to the wanted field * @return field object pair */ public static ExtendedField getConverterFieldByPathInHierarchy(final T obj, final String path) { - List steps = FieldPaths.parse(path); - if (Lists.isEmpty(steps)) { - return ExtendedField.EMPTY; - } - Field resultField = null; - Object resultObject = obj; - Class currentClass = resultObject.getClass(); - for (Step step : steps) { - if (StepKind.PROPERTY == step.kind()) { - if (null != resultField && null != resultObject) { - resultObject = Fields.IgnoreAccess.get(resultObject, resultField); - } - if (null == resultObject) { - return ExtendedField.EMPTY; - } - currentClass = Classes.getFrom(resultObject); - resultField = Fields.getOneDeclaredInHierarchy(currentClass, step.selector()); - if (null != resultField && STATIC.isPresentOn(resultField)) { - return ExtendedField.EMPTY; - } - if (null == resultField && resultObject instanceof Map map) { - if (!map.containsKey(step.selector())) { - return ExtendedField.EMPTY; - } - resultObject = map.get(step.selector()); - continue; - } - if (null == resultField) { - return ExtendedField.EMPTY; - } - } else { - if (null != resultField && null != resultObject) { - resultObject = Fields.IgnoreAccess.get(resultObject, resultField); - } - resultObject = FieldPaths.navigate(resultObject, step); - resultField = null; - if (null == resultObject) { - return ExtendedField.EMPTY; - } - } - } - if (null == resultObject || null == resultField) { - return ExtendedField.EMPTY; - } - return of(resultField, resultObject); + return FieldPaths.resolveField(obj, path); } } diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java new file mode 100644 index 00000000..4f569838 --- /dev/null +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -0,0 +1,294 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.reflection; + +import static org.morphix.reflection.JavaModifier.STATIC; + +import java.lang.reflect.Field; + +/** + * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting + * the expression into strings. The same parser handles single paths and comma-separated alternatives. + * + * @author Radu Sebastian LAZIN + */ +final class FieldPathParser { + + private final String paths; + + private final int length; + + private final boolean alternatives; + + private final boolean findField; + + private int index; + + private boolean invalid; + + FieldPathParser(final String paths, final boolean alternatives, final boolean findField) { + this.paths = paths; + this.length = paths.length(); + this.alternatives = alternatives; + this.findField = findField; + } + + /** + * Resolves paths in order, stopping at the first match. A malformed alternative can be skipped if its end is + * unambiguous. An unterminated bracket or quoted selector consumes the remainder of the expression. + * + * @param root root object + * @return resolved value or extended field, or null + */ + Object resolve(final Object root) { + while (hasNext()) { + if (alternatives) { + skipWhitespace(); + if (consume(',')) { + continue; + } + } + if (!hasNext()) { + break; + } + invalid = false; + Object result = readPath(root); + if (!alternatives) { + return !invalid && !hasNext() ? result : null; + } + skipWhitespace(); + if (hasNext() && ',' != peek()) { + invalid = true; + skipInvalidPath(); + } + if (!invalid && null != result) { + return result; + } + consume(','); + } + return null; + } + + private Object readPath(final Object root) { + Object value = root; + if ('[' != peek()) { + value = readProperty(value); + } + while (hasNext() && !invalid) { + if (consume('[')) { + value = readBracket(value); + } else if (consume('.')) { + value = readProperty(value); + } else { + break; + } + } + return invalid ? null : value; + } + + private Object readProperty(final Object obj) { + int start = index; + while (hasNext() && !isPropertyDelimiter(peek())) { + ++index; + } + int end = index; + if (alternatives && (!hasNext() || ',' == peek())) { + end = trimEnd(start, end); + } + if (start == end) { + return fail(); + } + if (null == obj) { + return null; + } + String name = paths.substring(start, end); + if (!findField) { + return FieldPaths.readProperty(obj, name); + } + Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); + if (null == field) { + return atPathEnd() ? null : FieldPaths.readMapKey(obj, name); + } + if (STATIC.isPresentOn(field)) { + return null; + } + if (atPathEnd()) { + return ExtendedField.of(field, obj); + } + return Fields.IgnoreAccess.get(obj, field); + } + + private Object readBracket(final Object obj) { + if (!hasNext()) { + return fail(); + } + char ch = peek(); + Object value; + if (isQuote(ch)) { + ++index; + String key = readQuoted(ch); + if (invalid) { + return null; + } + if (!consume(']')) { + skipBracket(); + return fail(); + } + value = FieldPaths.readMapKey(obj, key); + } else { + int start = index; + boolean numeric = true; + while (hasNext() && ']' != peek()) { + ch = peek(); + if ('[' == ch || isQuote(ch)) { + skipBracket(); + return fail(); + } + numeric &= Character.isDigit(ch); + ++index; + } + int end = index; + if (!consume(']') || start == end) { + return fail(); + } + if (numeric) { + try { + int elementIndex = Integer.parseInt(paths, start, end, 10); + value = FieldPaths.readIndex(obj, elementIndex); + } catch (NumberFormatException e) { + return fail(); + } + } else { + value = FieldPaths.readMapKey(obj, paths.substring(start, end)); + } + } + return findField && atPathEnd() ? null : value; + } + + private String readQuoted(final char quote) { + int start = index; + StringBuilder builder = null; + while (hasNext()) { + char ch = peek(); + if (quote == ch) { + String key = null == builder ? paths.substring(start, index) : builder.append(paths, start, index).toString(); + ++index; + return key; + } + if ('\\' == ch) { + if (null == builder) { + builder = new StringBuilder(); + } + builder.append(paths, start, index); + ++index; + if (!hasNext()) { + invalid = true; + return null; + } + builder.append(peek()); + start = index + 1; + } + ++index; + } + invalid = true; + return null; + } + + /** + * Recovers at a top-level comma, using the same quote and bracket rules as normal parsing. + */ + private void skipInvalidPath() { + while (hasNext() && ',' != peek()) { + if (consume('[')) { + skipBracket(); + } else { + ++index; + } + } + } + + /** + * Consumes the remainder of a bracket, including nested malformed brackets and quoted selectors. + */ + private void skipBracket() { + int depth = 1; + while (hasNext() && 0 < depth) { + char ch = peek(); + ++index; + if (isQuote(ch)) { + readQuoted(ch); + } else if ('[' == ch) { + ++depth; + } else if (']' == ch) { + --depth; + } + } + } + + private boolean atPathEnd() { + if (!hasNext()) { + return true; + } + if (!alternatives) { + return false; + } + int end = index; + while (end < length && paths.charAt(end) <= ' ') { + ++end; + } + return end == length || ',' == paths.charAt(end); + } + + private boolean isPropertyDelimiter(final char ch) { + return '.' == ch || '[' == ch || ']' == ch || (alternatives && ',' == ch); + } + + private static boolean isQuote(final char ch) { + return '\'' == ch || '"' == ch; + } + + private boolean hasNext() { + return index < length; + } + + private char peek() { + return paths.charAt(index); + } + + private boolean consume(final char ch) { + if (hasNext() && ch == peek()) { + ++index; + return true; + } + return false; + } + + private void skipWhitespace() { + while (hasNext() && peek() <= ' ') { + ++index; + } + } + + private int trimEnd(final int start, final int end) { + int result = end; + while (start < result && paths.charAt(result - 1) <= ' ') { + --result; + } + return result; + } + + private Object fail() { + invalid = true; + return null; + } +} diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 5c76742c..07ce9c5e 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -14,339 +14,112 @@ import java.lang.reflect.Array; import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.List; import java.util.Map; import org.morphix.lang.JavaObjects; -import org.morphix.lang.collections.Lists; /** - * Parses and resolves JSON Path-style selectors for field and container access (properties, array or list indices, and - * map keys). + * Resolves field paths using dot notation for properties and bracket notation for array/list indices and map keys. + * Multiple paths can be separated by commas outside bracket selectors. * * @author Radu Sebastian LAZIN */ public interface FieldPaths { /** - * Kind of path step. - */ - enum StepKind { - - /** - * A property or map key accessed with dot notation. - */ - PROPERTY, - - /** - * A zero-based index into an array or list. - */ - INDEX, - - /** - * A map key from bracket notation. - */ - KEY - } - - /** - * One step in a path expression. + * Resolves a single path to its value. + * + * @param value type * - * @param kind step kind - * @param selector property name, index text, or map key + * @param root root object + * @param path field path + * @return value or null if the path cannot be resolved */ - record Step(StepKind kind, String selector) { - // empty + static U resolveValue(final Object root, final String path) { + return JavaObjects.cast(resolve(root, path, false, false)); } /** - * Resolves the value at the given path starting from {@code root}, using the same rules as - * {@link Fields.Safe#getByPath(Object, String)}. + * Resolves the first non-null value in a comma-separated list of paths. Empty alternatives are ignored. * * @param value type * - * @param root start object - * @param path path expression - * @return value at the path, or {@code null} if the path is empty, invalid, or not found + * @param root root object + * @param paths alternative field paths + * @return first non-null value or null */ - static U resolveValue(final Object root, final String path) { - List steps = parse(path); - if (Lists.isEmpty(steps)) { - return null; - } - Object current = root; - for (Step step : steps) { - current = navigate(current, step); - if (null == current) { - break; - } - } - return JavaObjects.cast(current); + static U resolveValues(final Object root, final String paths) { + return JavaObjects.cast(resolve(root, paths, true, false)); } /** - * Parses a path into steps. Returns an empty list for an empty path, or {@code null} when the expression is invalid. + * Finds the first non-static reflective field and its owning object in a comma-separated list of paths. + * The final field is not read; a field with a null value can therefore be found. Paths ending at a container + * element rather than a reflective field are not matches. * - * @param path path expression - * @return parsed steps, empty list for {@code ""}, or {@code null} if invalid + * @param root root object + * @param paths alternative field paths + * @return field and its owning object, or {@link ExtendedField#EMPTY} */ - static List parse(final String path) { - if (path.isEmpty()) { - return List.of(); - } - List steps = new ArrayList<>(); - int index = 0; - int length = path.length(); - while (index < length) { - if (path.charAt(index) == '.') { - return null; - } - int propertyStart = index; - while (index < length) { - char ch = path.charAt(index); - if (ch == '.' || ch == '[') { - break; - } - index++; - } - if (propertyStart < index) { - steps.add(new Step(StepKind.PROPERTY, path.substring(propertyStart, index))); - } - index = parseBracketSteps(path, index, length, steps); - if (index < 0) { - return null; - } - if (index < length) { - if (path.charAt(index) != '.') { - return null; - } - index++; - if (index >= length) { - steps.add(new Step(StepKind.PROPERTY, "")); - return steps; - } - } - } - return steps; + static ExtendedField resolveField(final Object root, final String paths) { + ExtendedField field = JavaObjects.cast(resolve(root, paths, true, true)); + return null == field ? ExtendedField.EMPTY : field; } - /** - * Splits a comma-separated list of paths, ignoring commas inside {@code [...]} segments. - * - * @param paths comma-separated path expressions - * @return trimmed non-empty paths, or an empty list when nothing remains after trimming - */ - static List split(final String paths) { - if (paths.isEmpty()) { - return List.of(); - } - List result = new ArrayList<>(); - StringBuilder current = new StringBuilder(); - int bracketDepth = 0; - boolean inSingleQuote = false; - boolean inDoubleQuote = false; - for (int i = 0; i < paths.length(); ++i) { - char ch = paths.charAt(i); - if (inSingleQuote) { - current.append(ch); - if (ch == '\'' && (i == 0 || paths.charAt(i - 1) != '\\')) { - inSingleQuote = false; - } - continue; - } - if (inDoubleQuote) { - current.append(ch); - if (ch == '"' && (i == 0 || paths.charAt(i - 1) != '\\')) { - inDoubleQuote = false; - } - continue; - } - if (ch == '\'') { - inSingleQuote = true; - current.append(ch); - continue; - } - if (ch == '"') { - inDoubleQuote = true; - current.append(ch); - continue; - } - if (ch == '[') { - bracketDepth++; - current.append(ch); - continue; - } - if (ch == ']') { - bracketDepth--; - current.append(ch); - continue; - } - if (ch == ',' && bracketDepth == 0) { - String path = current.toString().trim(); - if (!path.isEmpty()) { - result.add(path); - } - current.setLength(0); - continue; - } - current.append(ch); - } - String path = current.toString().trim(); - if (!path.isEmpty()) { - result.add(path); + private static Object resolve(final Object root, final String paths, final boolean alternatives, final boolean findField) { + if (null == root || null == paths || paths.isEmpty()) { + return null; } - return result; + return new FieldPathParser(paths, alternatives, findField).resolve(root); } /** - * Applies a single step to the current value. + * Reads a property, preferring declared fields over map keys. * - * @param current current value - * @param step step to apply - * @return next value, or {@code null} if navigation fails - */ - static Object navigate(final Object current, final Step step) { - return switch (step.kind()) { - case PROPERTY -> readProperty(current, step.selector()); - case INDEX -> readIndex(current, step.selector()); - case KEY -> readMapKey(current, step.selector()); - }; - } - - /** - * @see StepKind#PROPERTY + * @param obj owning object + * @param name property name + * @return value or null */ - static Object readProperty(final Object current, final String propertyName) { - if (null == current || null == propertyName || propertyName.isEmpty()) { + static Object readProperty(final Object obj, final String name) { + if (null == obj || null == name || name.isEmpty()) { return null; } - Class cls = Classes.getFrom(current); - Field field = Fields.Unchecked.getOneDeclaredInHierarchy(cls, propertyName); - if (null != field) { - return Fields.Safe.get(current, field); - } - if (current instanceof Map map) { - return map.get(propertyName); - } - return null; + Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); + return null == field ? readMapKey(obj, name) : Fields.Safe.get(obj, field); } /** - * @see StepKind#INDEX + * Reads a zero-based array or list index. + * + * @param obj container + * @param index element index + * @return element or null */ - static Object readIndex(final Object current, final String indexText) { - if (null == current || null == indexText) { + static Object readIndex(final Object obj, final int index) { + if (null == obj || index < 0) { return null; } - int index; - try { - index = Integer.parseInt(indexText); - } catch (NumberFormatException e) { - return null; - } - if (index < 0) { - return null; - } - if (current instanceof List list) { + if (obj instanceof List list) { return index < list.size() ? list.get(index) : null; } - if (current.getClass().isArray()) { - int length = Array.getLength(current); - return index < length ? Array.get(current, index) : null; + if (obj.getClass().isArray()) { + return index < Array.getLength(obj) ? Array.get(obj, index) : null; } return null; } /** - * @see StepKind#KEY + * Reads a string map key. + * + * @param obj container + * @param key map key + * @return value or null */ - static Object readMapKey(final Object current, final String key) { - if (null == current || null == key) { - return null; - } - if (current instanceof Map map) { + static Object readMapKey(final Object obj, final String key) { + if (null != key && obj instanceof Map map) { return map.get(key); } return null; } - - private static int parseBracketSteps(final String path, final int index, final int length, final List steps) { - int currentIndex = index; - while (currentIndex < length && path.charAt(currentIndex) == '[') { - ++currentIndex; - if (currentIndex >= length) { - return -1; - } - char ch = path.charAt(currentIndex); - if (ch == '\'' || ch == '"') { - int[] nextIndex = new int[1]; - String key = readQuoted(path, currentIndex, length, ch, nextIndex); - if (null == key) { - return -1; - } - steps.add(new Step(StepKind.KEY, key)); - currentIndex = nextIndex[0]; - } else { - int selectorStart = index; - while (currentIndex < length && path.charAt(currentIndex) != ']') { - ++currentIndex; - } - if (currentIndex >= length) { - return -1; - } - String selector = path.substring(selectorStart, currentIndex); - if (selector.isEmpty()) { - return -1; - } - if (isInteger(selector)) { - steps.add(new Step(StepKind.INDEX, selector)); - } else { - steps.add(new Step(StepKind.KEY, selector)); - } - } - if (currentIndex >= length || path.charAt(currentIndex) != ']') { - return -1; - } - ++currentIndex; - } - return currentIndex; - } - - private static boolean isInteger(final String text) { - if (text.isEmpty()) { - return false; - } - for (int i = 0; i < text.length(); ++i) { - if (!Character.isDigit(text.charAt(i))) { - return false; - } - } - return true; - } - - private static String readQuoted(final String path, final int start, final int length, final char quote, final int[] nextIndexOut) { - StringBuilder builder = new StringBuilder(); - int index = start + 1; - while (index < length) { - char ch = path.charAt(index); - if (ch == '\\') { - ++index; - if (index >= length) { - return null; - } - builder.append(path.charAt(index)); - index++; - continue; - } - if (ch == quote) { - ++index; - nextIndexOut[0] = index; - return builder.toString(); - } - builder.append(ch); - ++index; - } - return null; - } } diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index e27cf26e..9cc625f1 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -822,8 +822,8 @@ static U getByPaths(final T obj, final String... paths) { /** * Variation of {@link Safe#getByPaths(Object, String...)} with paths given as a comma separated list of paths in a - * single string. Each segment is {@linkplain String#trim() trimmed} after splitting on {@code ','}; empty segments are - * ignored. + * single string. Commas inside brackets are part of the selector. Each path is {@linkplain String#trim() trimmed}; empty + * alternatives are ignored. * * @param object type * @param field value type @@ -835,14 +835,7 @@ static U getByPaths(final T obj, final String... paths) { */ static U getByPaths(final T obj, final String paths) { Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); - if (paths.isEmpty()) { - return null; - } - List trimmedPaths = FieldPaths.split(paths); - if (trimmedPaths.isEmpty()) { - return null; - } - return getByPaths(obj, trimmedPaths.toArray(String[]::new)); + return FieldPaths.resolveValues(obj, paths); } /** diff --git a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java index b0a40d0b..a38062e0 100644 --- a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java +++ b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java @@ -17,6 +17,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.morphix.convert.Conversions.convertFrom; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.Test; /** @@ -142,4 +145,36 @@ void shouldDeepConvertStaticStringEvenIfPathMatches() { assertThat(dst.l, nullValue()); assertThat(dst.x, equalTo(TEST_LONG)); } + + public static class IndexedSource { + + List items; + + Map keyed; + } + + public static class IndexedDestination { + + @Src("items[0].s") + Long indexed; + + @Src("items[9].s,keyed['a,b'].s") + Long alternative; + } + + @Test + void shouldDeepConvertIndexedAndAlternativePaths() { + A first = new A(); + first.s = "10"; + A second = new A(); + second.s = "20"; + IndexedSource src = new IndexedSource(); + src.items = List.of(first); + src.keyed = Map.of("a,b", second); + + IndexedDestination dst = convertFrom(src, IndexedDestination::new); + + assertThat(dst.indexed, equalTo(10L)); + assertThat(dst.alternative, equalTo(20L)); + } } diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java new file mode 100644 index 00000000..1c2f2ea7 --- /dev/null +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -0,0 +1,116 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.convert.strategy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.morphix.reflection.ExtendedField; +import org.morphix.reflection.Fields; + +/** + * Test class for {@link FinderPathStrategy}. + * + * @author Radu Sebastian LAZIN + */ +class FinderPathStrategyTest { + + public static class Entry { + + public static String staticName = "static"; + + private String name; + + private Entry(final String name) { + this.name = name; + } + } + + public static class Source { + + private final Entry[] entries = { new Entry("array"), new Entry(null) }; + + private final List items = List.of(new Entry("list")); + + private final Map keyed = Map.of("a,b", new Entry("map"), "key", new Entry("plain")); + + private final Entry missing = null; + } + + @Test + void shouldFindFinalFieldAndItsOwnerThroughContainers() { + Source source = new Source(); + FinderPathStrategy strategy = new FinderPathStrategy(); + + assertField(strategy.find(source, List.of(), "entries[0].name"), source.entries[0], "array"); + assertField(strategy.find(source, List.of(), "items[0].name"), source.items.get(0), "list"); + assertField(strategy.find(source, List.of(), "keyed['a,b'].name"), source.keyed.get("a,b"), "map"); + assertField(strategy.find(source, List.of(), "keyed[key].name"), source.keyed.get("key"), "plain"); + assertField(strategy.find(source, List.of(), "keyed.key.name"), source.keyed.get("key"), "plain"); + assertField(strategy.find(source.entries, List.of(), "[0].name"), source.entries[0], "array"); + } + + @Test + void shouldFindFirstExistingFieldAmongAlternatives() { + Source source = new Source(); + ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, + " , missing.name, entries[9].name, keyed['a,b'].name, items[0].name "); + + assertField(field, source.keyed.get("a,b"), "map"); + } + + @Test + void shouldFindNullValuedFieldWithoutTryingFollowingAlternative() { + Source source = new Source(); + String paths = "entries[1].name,items[0].name"; + + ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, paths); + + assertField(field, source.entries[1], null); + assertThat(Fields.Safe.getByPaths(source, paths), equalTo("list")); + } + + @Test + void shouldRejectStaticFieldsAndContainerElementsAsTerminalFields() { + Source source = new Source(); + + for (String path : List.of("entries[0].staticName", "entries[0]", "keyed['a,b']", "keyed.key", + "missing.name", "entries[0].", "entries[0].name[0]")) { + assertThat(path, FinderPathStrategy.getConverterFieldByPathInHierarchy(source, path), + sameInstance(ExtendedField.EMPTY)); + } + assertThat(FinderPathStrategy.getConverterFieldByPathInHierarchy(null, "entries[0].name"), + sameInstance(ExtendedField.EMPTY)); + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0].staticName,items[0].name"), + source.items.get(0), "list"); + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0],items[0].name"), + source.items.get(0), "list"); + } + + private static void assertField(final ExtendedField field, final Entry owner, final String value) { + assertThat(field.getObject(), sameInstance(owner)); + assertThat(field.getName(), equalTo("name")); + assertThat(field.getField().getDeclaringClass(), equalTo(Entry.class)); + if (null == value) { + assertThat(field.getFieldValue(), nullValue()); + } else { + assertThat(field.getFieldValue(), equalTo(value)); + } + } +} diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 6a8269a3..1af42335 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -52,40 +52,73 @@ public WithContainers() { } @Test - void shouldParseDotSeparatedProperties() { - List steps = FieldPaths.parse("inner.value"); + void shouldRejectInvalidExpressions() { + WithContainers root = new WithContainers(); - assertThat(steps.size(), equalTo(2)); - assertThat(steps.get(0).kind(), equalTo(FieldPaths.StepKind.PROPERTY)); - assertThat(steps.get(0).selector(), equalTo("inner")); - assertThat(steps.get(1).selector(), equalTo("value")); + for (String path : List.of(".entries", "entries.", "entries..name", "entries.[0]", "entries[0", + "entries[]", "entries[0]]", "entries[0]name", "entries[2147483648]", "entries[0].name,items[0].name")) { + assertThat(path, FieldPaths.resolveValue(root, path), nullValue()); + } } @Test - void shouldParseArrayIndexAndProperty() { - List steps = FieldPaths.parse("entries[0].name"); + void shouldResolveAlternativesWithoutSplittingQuotedKeys() { + WithContainers root = new WithContainers(); - assertThat(steps.size(), equalTo(3)); - assertThat(steps.get(1).kind(), equalTo(FieldPaths.StepKind.INDEX)); - assertThat(steps.get(1).selector(), equalTo("0")); - assertThat(steps.get(2).selector(), equalTo("name")); + assertThat(FieldPaths.resolveValues(root, " , missing.name, items[9].name, data['a,b'], entries[0].name, "), + equalTo("commaKey")); + assertThat(FieldPaths.resolveValues(root, "data['missing,key'], items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, ", ,"), nullValue()); } @Test - void shouldReturnNullForInvalidExpression() { - assertThat(FieldPaths.parse(".inner"), nullValue()); - assertThat(FieldPaths.parse("entries[0"), nullValue()); - assertThat(FieldPaths.parse("entries[]"), nullValue()); + void shouldRecoverFromMalformedAlternatives() { + WithContainers root = new WithContainers(); + + assertThat(FieldPaths.resolveValues(root, ".bad,entries[],entries[0]] ,items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "entries[2147483648],items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "data['unterminated,items[0].name"), nullValue()); + assertThat(FieldPaths.resolveValues(root, "items[0].name,entries["), equalTo("fromList")); } @Test - void shouldSplitCommaSeparatedPathsOutsideBrackets() { - List paths = FieldPaths.split("entries[0].name,data['a,b'],items[1].name"); + void shouldResolveEscapedKeysAndFollowingAlternatives() { + WithContainers root = new WithContainers(); + root.data.put("a\\", "backslash"); + root.data.put("a'b", "quote"); + root.data.put("a]b", "bracket"); + root.data.put("", "empty"); + root.data.put("0", "zero"); + root.data.put("a,b", "comma"); + + assertThat(FieldPaths.resolveValue(root, "data['a\\\\']"), equalTo("backslash")); + assertThat(FieldPaths.resolveValues(root, "data['missing\\\\'],items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "data['a\\\\'],items[0].name"), equalTo("backslash")); + assertThat(FieldPaths.resolveValue(root, "data['a\\'b']"), equalTo("quote")); + assertThat(FieldPaths.resolveValue(root, "data[\"a]b\"]"), equalTo("bracket")); + assertThat(FieldPaths.resolveValue(root, "data['']"), equalTo("empty")); + assertThat(FieldPaths.resolveValue(root, "data['0']"), equalTo("zero")); + assertThat(FieldPaths.resolveValue(root, "data[a,b]"), equalTo("comma")); + assertThat(FieldPaths.resolveValues(root, "data[a,b],items[0].name"), equalTo("comma")); + } + + @Test + void shouldResolveRootContainersAndChainedIndices() { + assertThat(FieldPaths.resolveValue(new int[][] { { 10, 20 }, { 30, 40 } }, "[1][0]"), equalTo(30)); + assertThat(FieldPaths.resolveValue(List.of(List.of("value")), "[0][0]"), equalTo("value")); + assertThat(FieldPaths.resolveValue(Map.of("a.b", "value"), "['a.b']"), equalTo("value")); + assertThat(FieldPaths.resolveValue(Map.of("a,b", "value"), "a,b"), equalTo("value")); + } + + @Test + void shouldTrimOnlyCompleteAlternatives() { + WithContainers root = new WithContainers(); - assertThat(paths.size(), equalTo(3)); - assertThat(paths.get(0), equalTo("entries[0].name")); - assertThat(paths.get(1), equalTo("data['a,b']")); - assertThat(paths.get(2), equalTo("items[1].name")); + assertThat(FieldPaths.resolveValues(root, " entries[0].name "), equalTo("fromArray")); + assertThat(FieldPaths.resolveValues(root, " data['key'] "), equalTo("fromMap")); + assertThat(FieldPaths.resolveValue(root, " entries[0].name"), nullValue()); + assertThat(FieldPaths.resolveValue(root, "entries[0].name "), nullValue()); + assertThat(FieldPaths.resolveValues(root, "entries[0]. name,items[0].name"), equalTo("fromList")); } @Test diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 2b4bde62..6c5cf271 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -164,4 +164,21 @@ void shouldNotSplitOnCommaInsideBrackets() { assertThat(value, equalTo("commaKey")); } + @Test + void shouldResolveFallbackAfterMalformedAlternative() { + B b = new B(); + b.a = new A(); + b.a.x = TEST_STRING; + + assertThat(Fields.Safe.getByPaths(b, ".bad,keyed[],a.x"), equalTo(TEST_STRING)); + } + + @Test + void shouldResolveFallbackAfterEscapedBackslash() { + B b = new B(); + b.a = new A(); + b.a.x = TEST_STRING; + + assertThat(Fields.Safe.getByPaths(b, "keyed['missing\\\\'].x,a.x"), equalTo(TEST_STRING)); + } } From 8905a5e995fc2576dc1a0b0f14c3b395c0b1b70e Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 01:39:56 +0200 Subject: [PATCH 05/20] Formatting. --- src/main/java/org/morphix/reflection/FieldPaths.java | 6 +++--- src/main/java/org/morphix/reflection/Fields.java | 4 ++-- .../morphix/convert/strategy/FinderPathStrategyTest.java | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 07ce9c5e..df083cdb 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -54,9 +54,9 @@ static U resolveValues(final Object root, final String paths) { } /** - * Finds the first non-static reflective field and its owning object in a comma-separated list of paths. - * The final field is not read; a field with a null value can therefore be found. Paths ending at a container - * element rather than a reflective field are not matches. + * Finds the first non-static reflective field and its owning object in a comma-separated list of paths. The final field + * is not read; a field with a null value can therefore be found. Paths ending at a container element rather than a + * reflective field are not matches. * * @param root root object * @param paths alternative field paths diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index 9cc625f1..3168ea76 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -822,8 +822,8 @@ static U getByPaths(final T obj, final String... paths) { /** * Variation of {@link Safe#getByPaths(Object, String...)} with paths given as a comma separated list of paths in a - * single string. Commas inside brackets are part of the selector. Each path is {@linkplain String#trim() trimmed}; empty - * alternatives are ignored. + * single string. Commas inside brackets are part of the selector. Each path is {@linkplain String#trim() trimmed}; + * empty alternatives are ignored. * * @param object type * @param field value type diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java index 1c2f2ea7..b1055f66 100644 --- a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -35,6 +35,7 @@ public static class Entry { public static String staticName = "static"; + @SuppressWarnings("unused") private String name; private Entry(final String name) { @@ -50,6 +51,7 @@ public static class Source { private final Map keyed = Map.of("a,b", new Entry("map"), "key", new Entry("plain")); + @SuppressWarnings("unused") private final Entry missing = null; } From 0d61c0bd90d8b2f5bdbe56ae9395839c3ce445fa Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 01:58:58 +0200 Subject: [PATCH 06/20] Resolve map properties as keys instead of internal fields --- .../org/morphix/reflection/FieldPathParser.java | 6 +++++- .../java/org/morphix/reflection/FieldPaths.java | 6 ++---- .../convert/strategy/FinderPathStrategyTest.java | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java index 4f569838..3ad91e2f 100644 --- a/src/main/java/org/morphix/reflection/FieldPathParser.java +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -15,6 +15,7 @@ import static org.morphix.reflection.JavaModifier.STATIC; import java.lang.reflect.Field; +import java.util.Map; /** * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting @@ -115,9 +116,12 @@ private Object readProperty(final Object obj) { if (!findField) { return FieldPaths.readProperty(obj, name); } + if (obj instanceof Map map) { + return atPathEnd() ? null : map.get(name); + } Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); if (null == field) { - return atPathEnd() ? null : FieldPaths.readMapKey(obj, name); + return null; } if (STATIC.isPresentOn(field)) { return null; diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index df083cdb..b4d1039f 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -13,7 +13,6 @@ package org.morphix.reflection; import java.lang.reflect.Array; -import java.lang.reflect.Field; import java.util.List; import java.util.Map; @@ -75,7 +74,7 @@ private static Object resolve(final Object root, final String paths, final boole } /** - * Reads a property, preferring declared fields over map keys. + * Reads a property, treating maps as containers rather than reflective objects. * * @param obj owning object * @param name property name @@ -85,8 +84,7 @@ static Object readProperty(final Object obj, final String name) { if (null == obj || null == name || name.isEmpty()) { return null; } - Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); - return null == field ? readMapKey(obj, name) : Fields.Safe.get(obj, field); + return obj instanceof Map map ? map.get(name) : Fields.Safe.get(obj, name); } /** diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java index b1055f66..04d15355 100644 --- a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -17,6 +17,7 @@ import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -105,6 +106,19 @@ void shouldRejectStaticFieldsAndContainerElementsAsTerminalFields() { source.items.get(0), "list"); } + @Test + void shouldResolveMapKeysInsteadOfInternalFields() { + Map map = new HashMap<>(); + Entry entry = new Entry("map size"); + map.put("size", entry); + + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(map, "size.name"), entry, "map size"); + assertThat(FinderPathStrategy.getConverterFieldByPathInHierarchy(map, "size"), + sameInstance(ExtendedField.EMPTY)); + assertThat(Fields.Safe.getByPath(map, "size.name"), equalTo("map size")); + assertThat(Fields.Safe.getByPath(map, "threshold"), nullValue()); + } + private static void assertField(final ExtendedField field, final Entry owner, final String value) { assertThat(field.getObject(), sameInstance(owner)); assertThat(field.getName(), equalTo("name")); From 2df815c3c163c152b48a52f1549ed5b1c77f0012 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 02:00:04 +0200 Subject: [PATCH 07/20] More test coverage. --- .../reflection/FieldsSafeGetByPathTest.java | 151 ++++++++++++++++++ 1 file changed, 151 insertions(+) diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 989e6830..47e125a6 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -15,6 +15,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.LinkedHashMap; @@ -22,6 +23,9 @@ import java.util.Map; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.morphix.lang.collections.FastArrayList; /** @@ -37,6 +41,8 @@ class FieldsSafeGetByPathTest { private static final String NON_EXISTENT_FIELD = "$NonExistentField$"; + private final Data data = new Data(); + public static class WithTransformingGetter { public String value = FIELD_VALUE; @@ -184,4 +190,149 @@ public static class Wrapper { public WithIndexedContainers row; } + + private record Person(String name) { + // empty + } + + @SuppressWarnings("unused") + private static final class Data { + + private final Person person = new Person("Alice"); + + private final List persons = List.of( + new Person("Alice"), + new Person("Bob")); + + private final String[] array = { "Alice", "Bob" }; + + private final int[] numbers = { 10, 20, 30 }; + + private final int[][] matrix = { + { 10, 20 }, + { 30, 40 } + }; + + private final Map attributes = Map.of( + "name", "Alice", + "first.name", "Bob", + "a,b", "comma", + "a]b", "bracket", + "a'b", "quote", + "a\\b", "backslash", + "0", "zero", + "", "empty", + "size", "map size"); + + private final Object missing = null; + } + + @ParameterizedTest + @CsvSource({ + "person.name, Alice", + "persons[0].name, Alice", + "persons[1].name, Bob", + "array[0], Alice", + "array[1], Bob", + "attributes.name, Alice", + "attributes[name], Alice", + "attributes['name'], Alice", + "attributes[\"name\"], Alice", + "attributes['first.name'], Bob", + "attributes['0'], zero", + "attributes[''], empty", + "attributes.size, map size", + "attributes['a]b'], bracket" + }) + void shouldResolvePath(final String path, final String expected) { + var result = Fields.Safe.getByPath(data, path); + + assertThat(result, equalTo(expected)); + } + + @Test + void shouldResolvePrimitiveArrayElement() { + Integer result = Fields.Safe.getByPath(data, "numbers[1]"); + + assertThat(result, equalTo(20)); + } + + @Test + void shouldResolveNestedArrayElement() { + Integer result = Fields.Safe.getByPath(data, "matrix[1][0]"); + + assertThat(result, equalTo(30)); + } + + @Test + void shouldResolveKeyContainingComma() { + var result = Fields.Safe.getByPath(data, "attributes['a,b']"); + + assertThat(result, equalTo("comma")); + } + + @Test + void shouldResolveKeyContainingQuote() { + var result = Fields.Safe.getByPath(data, "attributes['a\\'b']"); + + assertThat(result, equalTo("quote")); + } + + @Test + void shouldResolveKeyContainingBackslash() { + var result = Fields.Safe.getByPath(data, "attributes['a\\\\b']"); + + assertThat(result, equalTo("backslash")); + } + + @Test + void shouldResolveRootList() { + List persons = List.of(new Person("Alice")); + + var result = Fields.Safe.getByPath(persons, "[0].name"); + + assertThat(result, equalTo("Alice")); + } + + @Test + void shouldResolveRootMap() { + Map map = Map.of("name", "Alice"); + + var result = Fields.Safe.getByPath(map, "['name']"); + + assertThat(result, equalTo("Alice")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + ".", + ".person", + "person.", + "person..name", + "person.[0]", + "persons[]", + "persons[", + "persons[0", + "persons[0]]", + "persons[-1]", + "persons[100]", + "persons[2147483648]", + "persons[0]name", + "persons[0].", + "attributes['name]", + "attributes['name'", + "attributes['name']name", + "attributes[unknown]", + "missing.name", + "missing[0]", + "person.unknown", + "unknown" + }) + void shouldReturnNullForInvalidOrUnresolvedPath(final String path) { + var result = Fields.Safe.getByPath(data, path); + + assertNull(result); + } } From b060c90f8c8f2cd038b1e18852b60af787e3e610 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 02:28:17 +0200 Subject: [PATCH 08/20] Refactor boolean parameters. --- .../morphix/reflection/FieldPathParser.java | 148 +++++++++++++++++- .../org/morphix/reflection/FieldPaths.java | 14 +- 2 files changed, 145 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java index 3ad91e2f..1b001fa7 100644 --- a/src/main/java/org/morphix/reflection/FieldPathParser.java +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -12,36 +12,96 @@ */ package org.morphix.reflection; -import static org.morphix.reflection.JavaModifier.STATIC; - import java.lang.reflect.Field; import java.util.Map; /** * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting - * the expression into strings. The same parser handles single paths and comma-separated alternatives. + * the expression into strings. + *

+ * The parser handles both single paths and comma-separated alternatives. * * @author Radu Sebastian LAZIN */ final class FieldPathParser { + /** + * Selects how the parser interprets paths and what it returns. + */ + enum Mode { + + /** + * Resolves one path to its value. + */ + SINGLE_VALUE, + + /** + * Resolves comma-separated paths to the first non-null value. + */ + ALTERNATIVE_VALUES, + + /** + * Resolves comma-separated paths to the first non-static field and its owner, even if the field value is null. + */ + ALTERNATIVE_FIELD + } + + /** + * Path expression being parsed. + */ private final String paths; + /** + * Length of the path expression. + */ private final int length; + /** + * Whether comma-separated alternative paths are accepted. + */ private final boolean alternatives; + /** + * Whether the result must be a reflective field and its owning object. + */ private final boolean findField; + /** + * Index of the next character to read from {@link #paths}. + */ private int index; + /** + * Whether the current alternative contains invalid syntax. + */ private boolean invalid; - FieldPathParser(final String paths, final boolean alternatives, final boolean findField) { + /** + * Creates a parser for the given expression and resolution mode. + * + * @param paths path expression + * @param mode resolution mode + */ + private FieldPathParser(final String paths, final Mode mode) { this.paths = paths; this.length = paths.length(); - this.alternatives = alternatives; - this.findField = findField; + this.alternatives = Mode.SINGLE_VALUE != mode; + this.findField = Mode.ALTERNATIVE_FIELD == mode; + } + + /** + * Resolves an expression using the requested mode. + * + * @param root root object + * @param paths path expression + * @param mode resolution mode + * @return resolved value or extended field, or null if the root is null, the expression is empty, or no path matches + */ + static Object resolve(final Object root, final String paths, final Mode mode) { + if (null == root || null == paths || paths.isEmpty()) { + return null; + } + return new FieldPathParser(paths, mode).resolve(root); } /** @@ -80,6 +140,12 @@ Object resolve(final Object root) { return null; } + /** + * Reads one path, resolving each property or bracket selector as it is consumed. + * + * @param root root object + * @return resolved value or extended field, or null if the path is invalid or cannot be resolved + */ private Object readPath(final Object root) { Object value = root; if ('[' != peek()) { @@ -97,6 +163,13 @@ private Object readPath(final Object root) { return invalid ? null : value; } + /** + * Reads a property name and resolves it against an object or map. In field mode, the final property produces an + * extended field without reading its value. + * + * @param obj object containing the property + * @return property value or extended field, or null if it cannot be resolved + */ private Object readProperty(final Object obj) { int start = index; while (hasNext() && !isPropertyDelimiter(peek())) { @@ -123,7 +196,7 @@ private Object readProperty(final Object obj) { if (null == field) { return null; } - if (STATIC.isPresentOn(field)) { + if (JavaModifier.STATIC.isPresentOn(field)) { return null; } if (atPathEnd()) { @@ -132,6 +205,12 @@ private Object readProperty(final Object obj) { return Fields.IgnoreAccess.get(obj, field); } + /** + * Reads a bracket selector as an array or list index, or as a map key. The opening bracket has already been consumed. + * + * @param obj container to read + * @return selected value, or null if the selector is invalid or cannot be resolved + */ private Object readBracket(final Object obj) { if (!hasNext()) { return fail(); @@ -179,6 +258,13 @@ private Object readBracket(final Object obj) { return findField && atPathEnd() ? null : value; } + /** + * Reads a quoted map key, replacing backslash escapes with the escaped characters. The opening quote has already been + * consumed. + * + * @param quote quote character that closes the key + * @return unescaped key, or null if the closing quote is missing + */ private String readQuoted(final char quote) { int start = index; StringBuilder builder = null; @@ -239,6 +325,11 @@ private void skipBracket() { } } + /** + * Checks whether the cursor is at the end of the current path, allowing trailing whitespace in alternative mode. + * + * @return true if the current path ends here + */ private boolean atPathEnd() { if (!hasNext()) { return true; @@ -253,22 +344,50 @@ private boolean atPathEnd() { return end == length || ',' == paths.charAt(end); } + /** + * Checks whether a character terminates a property name in the current mode. + * + * @param ch character to check + * @return true if the character terminates a property name + */ private boolean isPropertyDelimiter(final char ch) { return '.' == ch || '[' == ch || ']' == ch || (alternatives && ',' == ch); } + /** + * Checks whether a character can quote a map key. + * + * @param ch character to check + * @return true for a single or double quote + */ private static boolean isQuote(final char ch) { return '\'' == ch || '"' == ch; } + /** + * Checks whether the cursor has another character to read. + * + * @return true if the cursor is before the end of the expression + */ private boolean hasNext() { return index < length; } + /** + * Returns the character at the cursor without advancing it. + * + * @return current character + */ private char peek() { return paths.charAt(index); } + /** + * Consumes the next character if it matches the expected character. + * + * @param ch expected character + * @return true if the character matched and was consumed + */ private boolean consume(final char ch) { if (hasNext() && ch == peek()) { ++index; @@ -277,12 +396,22 @@ private boolean consume(final char ch) { return false; } + /** + * Skips whitespace at the cursor using the same character range as {@link String#trim()}. + */ private void skipWhitespace() { while (hasNext() && peek() <= ' ') { ++index; } } + /** + * Finds the end of a property name after removing trailing whitespace from the given range. + * + * @param start start of the property name, inclusive + * @param end end of the property name, exclusive + * @return end index after trailing whitespace is removed + */ private int trimEnd(final int start, final int end) { int result = end; while (start < result && paths.charAt(result - 1) <= ' ') { @@ -291,6 +420,11 @@ private int trimEnd(final int start, final int end) { return result; } + /** + * Marks the current alternative as invalid. + * + * @return null so callers can return the failed resolution + */ private Object fail() { invalid = true; return null; diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index b4d1039f..2e5460ba 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -17,6 +17,7 @@ import java.util.Map; import org.morphix.lang.JavaObjects; +import org.morphix.reflection.FieldPathParser.Mode; /** * Resolves field paths using dot notation for properties and bracket notation for array/list indices and map keys. @@ -36,7 +37,7 @@ public interface FieldPaths { * @return value or null if the path cannot be resolved */ static U resolveValue(final Object root, final String path) { - return JavaObjects.cast(resolve(root, path, false, false)); + return JavaObjects.cast(FieldPathParser.resolve(root, path, Mode.SINGLE_VALUE)); } /** @@ -49,7 +50,7 @@ static U resolveValue(final Object root, final String path) { * @return first non-null value or null */ static U resolveValues(final Object root, final String paths) { - return JavaObjects.cast(resolve(root, paths, true, false)); + return JavaObjects.cast(FieldPathParser.resolve(root, paths, Mode.ALTERNATIVE_VALUES)); } /** @@ -62,17 +63,10 @@ static U resolveValues(final Object root, final String paths) { * @return field and its owning object, or {@link ExtendedField#EMPTY} */ static ExtendedField resolveField(final Object root, final String paths) { - ExtendedField field = JavaObjects.cast(resolve(root, paths, true, true)); + ExtendedField field = JavaObjects.cast(FieldPathParser.resolve(root, paths, Mode.ALTERNATIVE_FIELD)); return null == field ? ExtendedField.EMPTY : field; } - private static Object resolve(final Object root, final String paths, final boolean alternatives, final boolean findField) { - if (null == root || null == paths || paths.isEmpty()) { - return null; - } - return new FieldPathParser(paths, alternatives, findField).resolve(root); - } - /** * Reads a property, treating maps as containers rather than reflective objects. * From 9750f19049bb62973582ddd79d5ac441ccbef7db Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 03:01:08 +0200 Subject: [PATCH 09/20] Refactor `getByPath` tests. --- .../morphix/reflection/FieldPathParser.java | 125 ++++++---- .../reflection/FieldsSafeGetByPathTest.java | 218 ++++-------------- .../MethodsUncheckedGetAllDeclaredTest.java | 5 + 3 files changed, 127 insertions(+), 221 deletions(-) diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java index 1b001fa7..eb47a15e 100644 --- a/src/main/java/org/morphix/reflection/FieldPathParser.java +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -105,28 +105,44 @@ static Object resolve(final Object root, final String paths, final Mode mode) { } /** - * Resolves paths in order, stopping at the first match. A malformed alternative can be skipped if its end is - * unambiguous. An unterminated bracket or quoted selector consumes the remainder of the expression. + * Resolves the expression according to the configured mode. * * @param root root object * @return resolved value or extended field, or null */ Object resolve(final Object root) { + return alternatives ? resolveAlternatives(root) : resolveSinglePath(root); + } + + /** + * Resolves one path, requiring the entire expression to be valid. + * + * @param root root object + * @return resolved value, or null if the path is invalid or cannot be resolved + */ + private Object resolveSinglePath(final Object root) { + Object result = readPath(root); + return !invalid && !hasNext() ? result : null; + } + + /** + * Resolves paths in order, stopping at the first match. A malformed alternative can be skipped if its end is + * unambiguous. An unterminated bracket or quoted selector consumes the remainder of the expression. + * + * @param root root object + * @return resolved value or extended field, or null if no alternative matches + */ + private Object resolveAlternatives(final Object root) { while (hasNext()) { - if (alternatives) { - skipWhitespace(); - if (consume(',')) { - continue; - } + skipWhitespace(); + if (consume(',')) { + continue; } if (!hasNext()) { - break; + return null; } invalid = false; Object result = readPath(root); - if (!alternatives) { - return !invalid && !hasNext() ? result : null; - } skipWhitespace(); if (hasNext() && ',' != peek()) { invalid = true; @@ -192,7 +208,8 @@ private Object readProperty(final Object obj) { if (obj instanceof Map map) { return atPathEnd() ? null : map.get(name); } - Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); + Class type = obj.getClass(); + Field field = Fields.Unchecked.getOneDeclaredInHierarchy(type, name); if (null == field) { return null; } @@ -215,47 +232,61 @@ private Object readBracket(final Object obj) { if (!hasNext()) { return fail(); } - char ch = peek(); - Object value; - if (isQuote(ch)) { - ++index; - String key = readQuoted(ch); - if (invalid) { - return null; - } - if (!consume(']')) { + Object value = isQuote(peek()) ? readQuotedKey(obj) : readUnquotedSelector(obj); + return findField && atPathEnd() ? null : value; + } + + /** + * Reads a quoted map key and its closing bracket. + * + * @param obj map containing the key + * @return map value, or null if the selector is invalid or the key is absent + */ + private Object readQuotedKey(final Object obj) { + char quote = peek(); + ++index; + String key = readQuoted(quote); + if (invalid) { + return null; + } + if (!consume(']')) { + skipBracket(); + return fail(); + } + return FieldPaths.readMapKey(obj, key); + } + + /** + * Reads an unquoted array or list index, or a map key, and its closing bracket. + * + * @param obj container to read + * @return selected value, or null if the selector is invalid or cannot be resolved + */ + private Object readUnquotedSelector(final Object obj) { + int start = index; + boolean numeric = true; + while (hasNext() && ']' != peek()) { + char ch = peek(); + if ('[' == ch || isQuote(ch)) { skipBracket(); return fail(); } - value = FieldPaths.readMapKey(obj, key); - } else { - int start = index; - boolean numeric = true; - while (hasNext() && ']' != peek()) { - ch = peek(); - if ('[' == ch || isQuote(ch)) { - skipBracket(); - return fail(); - } - numeric &= Character.isDigit(ch); - ++index; - } - int end = index; - if (!consume(']') || start == end) { + numeric &= Character.isDigit(ch); + ++index; + } + int end = index; + if (!consume(']') || start == end) { + return fail(); + } + if (numeric) { + try { + int elementIndex = Integer.parseInt(paths, start, end, 10); + return FieldPaths.readIndex(obj, elementIndex); + } catch (NumberFormatException e) { return fail(); } - if (numeric) { - try { - int elementIndex = Integer.parseInt(paths, start, end, 10); - value = FieldPaths.readIndex(obj, elementIndex); - } catch (NumberFormatException e) { - return fail(); - } - } else { - value = FieldPaths.readMapKey(obj, paths.substring(start, end)); - } } - return findField && atPathEnd() ? null : value; + return FieldPaths.readMapKey(obj, paths.substring(start, end)); } /** diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 47e125a6..fb3e50a2 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -18,15 +18,15 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; -import org.morphix.lang.collections.FastArrayList; /** * Test class for {@link Fields.Safe#getByPath(Object, String)}. @@ -39,8 +39,6 @@ class FieldsSafeGetByPathTest { private static final String GETTER_VALUE = "getterValue"; - private static final String NON_EXISTENT_FIELD = "$NonExistentField$"; - private final Data data = new Data(); public static class WithTransformingGetter { @@ -57,20 +55,6 @@ public static class WithNestedField { public WithTransformingGetter inner = new WithTransformingGetter(); } - public static class WithIndexedContainers { - - public String[] tags = { "alpha", "beta" }; - - public List codes = new FastArrayList<>(new String[] { "x", "y" }); - - public Map attributes = new LinkedHashMap<>(); - - public WithIndexedContainers() { - attributes.put("color", "blue"); - attributes.put("size", "large"); - } - } - @Test void shouldGetFieldAtFirstLevel() { WithNestedField obj = new WithNestedField(); @@ -80,64 +64,18 @@ void shouldGetFieldAtFirstLevel() { assertThat(result, equalTo(obj.inner)); } - @Test - void shouldGetNestedField() { - WithNestedField obj = new WithNestedField(); - - Object result = Fields.Safe.getByPath(obj, "inner.value"); + @ParameterizedTest + @MethodSource("getterPaths") + void shouldReadTheFieldAndNotTheGetter(final Object root, final String path) { + var result = Fields.Safe.getByPath(root, path); assertThat(result, equalTo(FIELD_VALUE)); } - @Test - void shouldReturnNullIfFieldDoesNotExistAtFirstLevel() { - WithNestedField obj = new WithNestedField(); - - Object result = Fields.Safe.getByPath(obj, NON_EXISTENT_FIELD); - - assertThat(result, nullValue()); - } - - @Test - void shouldReturnNullIfNestedFieldDoesNotExist() { - WithNestedField obj = new WithNestedField(); - - Object result = Fields.Safe.getByPath(obj, "inner." + NON_EXISTENT_FIELD); - - assertThat(result, nullValue()); - } - - @Test - void shouldReturnNullIfIntermediateFieldIsNull() { - WithNestedField obj = new WithNestedField(); - obj.inner = null; - - Object result = Fields.Safe.getByPath(obj, "inner.value"); - - assertThat(result, nullValue()); - } - - @Test - void shouldReturnNullForEmptyPath() { - Object result = Fields.Safe.getByPath(new WithNestedField(), ""); - - assertThat(result, nullValue()); - } - - @Test - void shouldReturnNullForPathWithTrailingDot() { - Object result = Fields.Safe.getByPath(new WithNestedField(), "inner."); - - assertThat(result, nullValue()); - } - - @Test - void shouldReadTheFieldAndNotTheGetterOnASingleSegmentPath() { - WithTransformingGetter obj = new WithTransformingGetter(); - - Object result = Fields.Safe.getByPath(obj, "value"); - - assertThat(result, equalTo(FIELD_VALUE)); + private static Stream getterPaths() { + return Stream.of( + Arguments.of(new WithTransformingGetter(), "value"), + Arguments.of(new WithNestedField(), "inner.value")); } @Test @@ -153,44 +91,6 @@ void shouldThrowWhenPathIsNull() { assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null")); } - @Test - void shouldGetValueByArrayIndexPath() { - WithIndexedContainers obj = new WithIndexedContainers(); - - assertThat(Fields.Safe.getByPath(obj, "tags[1]"), equalTo("beta")); - assertThat(Fields.Safe.getByPath(obj, "tags[0]"), equalTo("alpha")); - } - - @Test - void shouldGetValueByListIndexPath() { - WithIndexedContainers obj = new WithIndexedContainers(); - - assertThat(Fields.Safe.getByPath(obj, "codes[1]"), equalTo("y")); - } - - @Test - void shouldGetValueByMapKeyPath() { - WithIndexedContainers obj = new WithIndexedContainers(); - - assertThat(Fields.Safe.getByPath(obj, "attributes['color']"), equalTo("blue")); - assertThat(Fields.Safe.getByPath(obj, "attributes[size]"), equalTo("large")); - } - - @Test - void shouldGetNestedValueAfterIndexPath() { - WithIndexedContainers obj = new WithIndexedContainers(); - obj.tags = new String[] { "outer" }; - Wrapper wrapper = new Wrapper(); - wrapper.row = obj; - - assertThat(Fields.Safe.getByPath(wrapper, "row.tags[0]"), equalTo("outer")); - } - - public static class Wrapper { - - public WithIndexedContainers row; - } - private record Person(String name) { // empty } @@ -228,79 +128,49 @@ private static final class Data { } @ParameterizedTest - @CsvSource({ - "person.name, Alice", - "persons[0].name, Alice", - "persons[1].name, Bob", - "array[0], Alice", - "array[1], Bob", - "attributes.name, Alice", - "attributes[name], Alice", - "attributes['name'], Alice", - "attributes[\"name\"], Alice", - "attributes['first.name'], Bob", - "attributes['0'], zero", - "attributes[''], empty", - "attributes.size, map size", - "attributes['a]b'], bracket" - }) - void shouldResolvePath(final String path, final String expected) { + @MethodSource("resolvedPaths") + void shouldResolvePath(final String path, final Object expected) { var result = Fields.Safe.getByPath(data, path); assertThat(result, equalTo(expected)); } - @Test - void shouldResolvePrimitiveArrayElement() { - Integer result = Fields.Safe.getByPath(data, "numbers[1]"); - - assertThat(result, equalTo(20)); + private static Stream resolvedPaths() { + return Stream.of( + Arguments.of("person.name", "Alice"), + Arguments.of("persons[0]", new Person("Alice")), + Arguments.of("persons[0].name", "Alice"), + Arguments.of("persons[1].name", "Bob"), + Arguments.of("array[0]", "Alice"), + Arguments.of("array[1]", "Bob"), + Arguments.of("numbers[1]", 20), + Arguments.of("matrix[1][0]", 30), + Arguments.of("attributes.name", "Alice"), + Arguments.of("attributes[name]", "Alice"), + Arguments.of("attributes['name']", "Alice"), + Arguments.of("attributes[\"name\"]", "Alice"), + Arguments.of("attributes['first.name']", "Bob"), + Arguments.of("attributes['0']", "zero"), + Arguments.of("attributes['']", "empty"), + Arguments.of("attributes.size", "map size"), + Arguments.of("attributes['a]b']", "bracket"), + Arguments.of("attributes['a,b']", "comma"), + Arguments.of("attributes['a\\'b']", "quote"), + Arguments.of("attributes['a\\\\b']", "backslash")); } - @Test - void shouldResolveNestedArrayElement() { - Integer result = Fields.Safe.getByPath(data, "matrix[1][0]"); - - assertThat(result, equalTo(30)); - } - - @Test - void shouldResolveKeyContainingComma() { - var result = Fields.Safe.getByPath(data, "attributes['a,b']"); - - assertThat(result, equalTo("comma")); - } - - @Test - void shouldResolveKeyContainingQuote() { - var result = Fields.Safe.getByPath(data, "attributes['a\\'b']"); - - assertThat(result, equalTo("quote")); - } - - @Test - void shouldResolveKeyContainingBackslash() { - var result = Fields.Safe.getByPath(data, "attributes['a\\\\b']"); - - assertThat(result, equalTo("backslash")); - } - - @Test - void shouldResolveRootList() { - List persons = List.of(new Person("Alice")); - - var result = Fields.Safe.getByPath(persons, "[0].name"); + @ParameterizedTest + @MethodSource("rootPaths") + void shouldResolveRootContainer(final Object root, final String path, final Object expected) { + var result = Fields.Safe.getByPath(root, path); - assertThat(result, equalTo("Alice")); + assertThat(result, equalTo(expected)); } - @Test - void shouldResolveRootMap() { - Map map = Map.of("name", "Alice"); - - var result = Fields.Safe.getByPath(map, "['name']"); - - assertThat(result, equalTo("Alice")); + private static Stream rootPaths() { + return Stream.of( + Arguments.of(List.of(new Person("Alice")), "[0].name", "Alice"), + Arguments.of(Map.of("name", "Alice"), "['name']", "Alice")); } @ParameterizedTest diff --git a/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java b/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java index fc7e8e74..5d2a50bf 100644 --- a/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java +++ b/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java @@ -85,6 +85,11 @@ void shouldThrowNullPointerExceptionForNullClassWithPredicate() { @Test void shouldThrowNullPointerExceptionForNullPredicate() { + assertThrows(NullPointerException.class, () -> Methods.Unchecked.getAllDeclared(A.class, null)); + } + + @Test + void shouldThrowNullPointerExceptionForNullPredicateAndNoMethods() { assertThrows(NullPointerException.class, () -> Methods.Unchecked.getAllDeclared(C.class, null)); } From d139de4a2fa84b2467bf39c8b9b921d16088b328 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 03:15:34 +0200 Subject: [PATCH 10/20] More test coverage. --- .../morphix/reflection/FieldPathsTest.java | 209 +++++++++++------- .../reflection/FieldsSafeGetByPathsTest.java | 173 ++++++--------- 2 files changed, 194 insertions(+), 188 deletions(-) diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 1af42335..1cd0d35a 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -19,8 +19,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.morphix.lang.collections.FastArrayList; /** @@ -37,7 +42,7 @@ public static class Entry { public static class WithContainers { - public Entry[] entries = { new Entry() }; + public Entry[] entries = { new Entry(), new Entry() }; public List items = new FastArrayList<>(new Entry[] { new Entry() }); @@ -45,120 +50,164 @@ public static class WithContainers { public WithContainers() { entries[0].name = "fromArray"; + entries[1].name = "second"; items.get(0).name = "fromList"; data.put("key", "fromMap"); data.put("a,b", "commaKey"); + data.put("a\\", "backslash"); + data.put("a'b", "quote"); + data.put("a]b", "bracket"); + data.put("", "empty"); + data.put("0", "zero"); + data.put("say \"hi\"", "quoted"); } } - @Test - void shouldRejectInvalidExpressions() { - WithContainers root = new WithContainers(); + private final WithContainers root = new WithContainers(); + + @ParameterizedTest + @ValueSource( + strings = { + "", + ".entries", + ".bad", + "entries.", + "entries..name", + "entries.[0]", + "entries[0", + "entries[]", + "entries[0]]", + "entries[0]name", + "entries[2147483648]", + "entries[-1]", + "entries[notAnIndex]", + "entries[0].name,items[0].name", + "items[9].name", + " entries[0].name", + "entries[0].name " + }) + void shouldReturnNullForInvalidOrUnresolvedSinglePath(final String path) { + var result = FieldPaths.resolveValue(root, path); + + assertThat(path, result, nullValue()); + } - for (String path : List.of(".entries", "entries.", "entries..name", "entries.[0]", "entries[0", - "entries[]", "entries[0]]", "entries[0]name", "entries[2147483648]", "entries[0].name,items[0].name")) { - assertThat(path, FieldPaths.resolveValue(root, path), nullValue()); - } + @ParameterizedTest + @MethodSource("alternativePaths") + void shouldResolveFirstMatchingAlternative(final String paths, final String expected) { + var result = FieldPaths.resolveValues(root, paths); + + assertThat(result, equalTo(expected)); } - @Test - void shouldResolveAlternativesWithoutSplittingQuotedKeys() { - WithContainers root = new WithContainers(); + private static Stream alternativePaths() { + return Stream.of( + Arguments.of(" , missing.name, items[9].name, data['a,b'], entries[0].name, ", "commaKey"), + Arguments.of("data['missing,key'], items[0].name", "fromList"), + Arguments.of(".bad,entries[],entries[0]] ,items[0].name", "fromList"), + Arguments.of("entries[2147483648],items[0].name", "fromList"), + Arguments.of("items[0].name,entries[", "fromList"), + Arguments.of("data['missing\\\\'],items[0].name", "fromList"), + Arguments.of("data['a\\\\'],items[0].name", "backslash"), + Arguments.of("data[a,b],items[0].name", "commaKey"), + Arguments.of(" entries[0].name ", "fromArray"), + Arguments.of(" data['key'] ", "fromMap"), + Arguments.of("entries[0]. name,items[0].name", "fromList")); + } - assertThat(FieldPaths.resolveValues(root, " , missing.name, items[9].name, data['a,b'], entries[0].name, "), - equalTo("commaKey")); - assertThat(FieldPaths.resolveValues(root, "data['missing,key'], items[0].name"), equalTo("fromList")); - assertThat(FieldPaths.resolveValues(root, ", ,"), nullValue()); + @ParameterizedTest + @ValueSource( + strings = { + ", ,", + "data['unterminated,items[0].name" + }) + void shouldReturnNullWhenNoAlternativeMatches(final String paths) { + var result = FieldPaths.resolveValues(root, paths); + + assertThat(result, nullValue()); } - @Test - void shouldRecoverFromMalformedAlternatives() { - WithContainers root = new WithContainers(); + @ParameterizedTest + @MethodSource("singlePaths") + void shouldResolveSinglePath(final String path, final String expected) { + var result = FieldPaths.resolveValue(root, path); - assertThat(FieldPaths.resolveValues(root, ".bad,entries[],entries[0]] ,items[0].name"), equalTo("fromList")); - assertThat(FieldPaths.resolveValues(root, "entries[2147483648],items[0].name"), equalTo("fromList")); - assertThat(FieldPaths.resolveValues(root, "data['unterminated,items[0].name"), nullValue()); - assertThat(FieldPaths.resolveValues(root, "items[0].name,entries["), equalTo("fromList")); + assertThat(result, equalTo(expected)); } - @Test - void shouldResolveEscapedKeysAndFollowingAlternatives() { - WithContainers root = new WithContainers(); - root.data.put("a\\", "backslash"); - root.data.put("a'b", "quote"); - root.data.put("a]b", "bracket"); - root.data.put("", "empty"); - root.data.put("0", "zero"); - root.data.put("a,b", "comma"); - - assertThat(FieldPaths.resolveValue(root, "data['a\\\\']"), equalTo("backslash")); - assertThat(FieldPaths.resolveValues(root, "data['missing\\\\'],items[0].name"), equalTo("fromList")); - assertThat(FieldPaths.resolveValues(root, "data['a\\\\'],items[0].name"), equalTo("backslash")); - assertThat(FieldPaths.resolveValue(root, "data['a\\'b']"), equalTo("quote")); - assertThat(FieldPaths.resolveValue(root, "data[\"a]b\"]"), equalTo("bracket")); - assertThat(FieldPaths.resolveValue(root, "data['']"), equalTo("empty")); - assertThat(FieldPaths.resolveValue(root, "data['0']"), equalTo("zero")); - assertThat(FieldPaths.resolveValue(root, "data[a,b]"), equalTo("comma")); - assertThat(FieldPaths.resolveValues(root, "data[a,b],items[0].name"), equalTo("comma")); + private static Stream singlePaths() { + return Stream.of( + Arguments.of("entries[0].name", "fromArray"), + Arguments.of("entries[1].name", "second"), + Arguments.of("items[0].name", "fromList"), + Arguments.of("data['key']", "fromMap"), + Arguments.of("data[key]", "fromMap"), + Arguments.of("data['a,b']", "commaKey"), + Arguments.of("data[a,b]", "commaKey"), + Arguments.of("data['a\\\\']", "backslash"), + Arguments.of("data['a\\'b']", "quote"), + Arguments.of("data[\"a]b\"]", "bracket"), + Arguments.of("data['']", "empty"), + Arguments.of("data['0']", "zero"), + Arguments.of("data['say \\\"hi\\\"']", "quoted")); } - @Test - void shouldResolveRootContainersAndChainedIndices() { - assertThat(FieldPaths.resolveValue(new int[][] { { 10, 20 }, { 30, 40 } }, "[1][0]"), equalTo(30)); - assertThat(FieldPaths.resolveValue(List.of(List.of("value")), "[0][0]"), equalTo("value")); - assertThat(FieldPaths.resolveValue(Map.of("a.b", "value"), "['a.b']"), equalTo("value")); - assertThat(FieldPaths.resolveValue(Map.of("a,b", "value"), "a,b"), equalTo("value")); + @ParameterizedTest + @MethodSource("rootPaths") + void shouldResolveRootContainer(final Object container, final String path, final Object expected) { + var result = FieldPaths.resolveValue(container, path); + + assertThat(result, equalTo(expected)); + } + + private static Stream rootPaths() { + return Stream.of( + Arguments.of(new int[][] { { 10, 20 }, { 30, 40 } }, "[1][0]", 30), + Arguments.of(List.of(List.of("value")), "[0][0]", "value"), + Arguments.of(Map.of("a.b", "value"), "['a.b']", "value"), + Arguments.of(Map.of("a,b", "value"), "a,b", "value")); } @Test - void shouldTrimOnlyCompleteAlternatives() { - WithContainers root = new WithContainers(); + void shouldReturnNullForNullRoot() { + var result = FieldPaths.resolveValue(null, "entries[0]"); - assertThat(FieldPaths.resolveValues(root, " entries[0].name "), equalTo("fromArray")); - assertThat(FieldPaths.resolveValues(root, " data['key'] "), equalTo("fromMap")); - assertThat(FieldPaths.resolveValue(root, " entries[0].name"), nullValue()); - assertThat(FieldPaths.resolveValue(root, "entries[0].name "), nullValue()); - assertThat(FieldPaths.resolveValues(root, "entries[0]. name,items[0].name"), equalTo("fromList")); + assertThat(result, nullValue()); } @Test - void shouldResolveArrayListAndMapPaths() { - WithContainers root = new WithContainers(); + void shouldResolveTerminalListElement() { + var result = FieldPaths.resolveValue(root, "items[0]"); - assertThat(FieldPaths.resolveValue(root, "entries[0].name"), equalTo("fromArray")); - assertThat(FieldPaths.resolveValue(root, "items[0].name"), equalTo("fromList")); - assertThat(FieldPaths.resolveValue(root, "data['key']"), equalTo("fromMap")); - assertThat(FieldPaths.resolveValue(root, "data['a,b']"), equalTo("commaKey")); - assertThat(FieldPaths.resolveValue(root, "data[key]"), equalTo("fromMap")); - assertThat(FieldPaths.resolveValue(root, "items[9].name"), nullValue()); + assertThat(result, equalTo(root.items.get(0))); } - @Test - void shouldReturnNullForEmptyOrInvalidResolve() { - WithContainers root = new WithContainers(); + @ParameterizedTest + @MethodSource("invalidProperties") + void shouldReturnNullForInvalidProperty(final Object obj, final String name) { + var result = FieldPaths.readProperty(obj, name); + + assertThat(result, nullValue()); + } - assertThat(FieldPaths.resolveValue(root, ""), nullValue()); - assertThat(FieldPaths.resolveValue(root, ".bad"), nullValue()); - assertThat(FieldPaths.resolveValue(root, "entries[-1]"), nullValue()); - assertThat(FieldPaths.resolveValue(null, "entries[0]"), nullValue()); - assertThat(FieldPaths.resolveValue(root, "entries[notAnIndex]"), nullValue()); - assertThat(FieldPaths.resolveValue(root, "items[0]"), equalTo(root.items.get(0))); + private static Stream invalidProperties() { + return Stream.of( + Arguments.of(null, "key"), + Arguments.of(new WithContainers(), null), + Arguments.of(new WithContainers(), "")); } @Test - void shouldUnescapeQuotedMapKeys() { - WithContainers root = new WithContainers(); - root.data.put("say \"hi\"", "quoted"); + void shouldReturnNullForNegativeIndex() { + var result = FieldPaths.readIndex(root.items, -1); - assertThat(FieldPaths.resolveValue(root, "data['say \\\"hi\\\"']"), equalTo("quoted")); + assertThat(result, nullValue()); } @Test - void shouldResolveNestedArrayIndices() { - WithContainers root = new WithContainers(); - root.entries = new Entry[] { new Entry(), new Entry() }; - root.entries[1].name = "second"; + void shouldReturnNullForNullMapKey() { + var result = FieldPaths.readMapKey(root.data, null); - assertThat(FieldPaths.resolveValue(root, "entries[1].name"), equalTo("second")); + assertThat(result, nullValue()); } } diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 6c5cf271..a2d47fee 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -17,10 +17,12 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Test class for {@link Fields.Safe#getByPaths(Object, String...)} and {@link Fields.Safe#getByPaths(Object, String)}. @@ -29,156 +31,111 @@ */ class FieldsSafeGetByPathsTest { - private static final String TEST_STRING = "testString"; - - public static class A { - public String x; + private record Person(String name) { + // empty } - public static class B { + @SuppressWarnings("unused") + private static final class Data { - public A a; + private final Person person = new Person("Alice"); - public Map keyed = new LinkedHashMap<>(); - } + private final List persons = List.of(new Person("Alice")); - @Test - void shouldGetFieldByPaths() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; + private final Object missing = null; - String x = Fields.Safe.getByPaths(b, "x.y,a.x"); + private final Map attributes = Map.of("a,b", "commaKey"); - assertThat(x, equalTo(TEST_STRING)); + private final Map keyed = Map.of("a,b", new Person("commaKey")); } - @Test - void shouldGetFieldByPathsWhenCommaSeparatedPathsHaveWhitespace() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; - - String x = Fields.Safe.getByPaths(b, "x.y , a.x"); - - assertThat(x, equalTo(TEST_STRING)); + private final Data data = new Data(); + + @ParameterizedTest + @ValueSource( + strings = { + "person.name", + "unknown,person.name", + "missing.name,person.name", + "missing[0].name,person.name", + "persons[100].name,person.name", + "unknown, persons[0].name", + ",,,person.name,,,", + " , , person.name , ", + "attributes['unknown,key'],person.name", + "unknown , person.name", + ".bad,attributes[],person.name", + "attributes['missing\\\\'].name,person.name" + }) + void shouldResolveFirstNonNullPath(final String paths) { + var result = Fields.Safe.getByPaths(data, paths); + + assertThat(result, equalTo("Alice")); } @Test - void shouldGetFieldByPathsWithVarargs() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; - - String x = Fields.Safe.getByPaths(b, "x.y", "a.x"); + void shouldResolveFirstNonNullPathWithVarargs() { + var result = Fields.Safe.getByPaths(data, "unknown", "person.name"); - assertThat(x, equalTo(TEST_STRING)); + assertThat(result, equalTo("Alice")); } @Test - void shouldGetFieldByPathsAtFirstLevel() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; + void shouldResolveFieldAtFirstLevel() { + var result = Fields.Safe.getByPaths(data, "person"); - A result = Fields.Safe.getByPaths(b, "a"); - - assertThat(result, equalTo(a)); + assertThat(result, equalTo(data.person)); } - @Test - void shouldReturnNullIfFieldDoesNotExist() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; - - A result = Fields.Safe.getByPaths(b, "z"); + @ParameterizedTest + @ValueSource( + strings = { + "", + " , , ", + "unknown", + "missing.name", + "persons[100].name" + }) + void shouldReturnNullWhenNoPathResolves(final String paths) { + var result = Fields.Safe.getByPaths(data, paths); assertThat(result, nullValue()); } @Test void shouldThrowWhenCommaSeparatedPathsAreNull() { - B b = new B(); - - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, (String) null)); + ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, (String) null)); assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null")); } @Test - void shouldReturnNullForEmptySearch() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; - - A result = Fields.Safe.getByPaths(b, ""); - - assertThat(result, nullValue()); - - result = Fields.Safe.getByPaths(b, new String[] { }); - - assertThat(result, nullValue()); - - result = Fields.Safe.getByPaths(b, " , , "); + void shouldReturnNullForEmptyVarargs() { + var result = Fields.Safe.getByPaths(data, new String[] { }); assertThat(result, nullValue()); } @Test void shouldThrowWhenAPathIsNull() { - A a = new A(); - a.x = TEST_STRING; - B b = new B(); - b.a = a; - - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, new String[] { null })); + ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, new String[] { null })); assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null")); } @Test void shouldThrowWhenPathsArrayIsNull() { - B b = new B(); - - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, (String[]) null)); + ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, (String[]) null)); assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null")); } - @Test - void shouldNotSplitOnCommaInsideBrackets() { - A fromMap = new A(); - fromMap.x = "commaKey"; - A fromDot = new A(); - fromDot.x = "dotPath"; - B b = new B(); - b.keyed.put("a,b", fromMap); - b.a = fromDot; - - String value = Fields.Safe.getByPaths(b, "keyed['a,b'].x,a.x"); - - assertThat(value, equalTo("commaKey")); - } - - @Test - void shouldResolveFallbackAfterMalformedAlternative() { - B b = new B(); - b.a = new A(); - b.a.x = TEST_STRING; - - assertThat(Fields.Safe.getByPaths(b, ".bad,keyed[],a.x"), equalTo(TEST_STRING)); - } - - @Test - void shouldResolveFallbackAfterEscapedBackslash() { - B b = new B(); - b.a = new A(); - b.a.x = TEST_STRING; + @ParameterizedTest + @ValueSource( + strings = { + "attributes['a,b'],person.name", + "keyed['a,b'].name,person.name" + }) + void shouldNotSplitOnCommaInsideBrackets(final String paths) { + var result = Fields.Safe.getByPaths(data, paths); - assertThat(Fields.Safe.getByPaths(b, "keyed['missing\\\\'].x,a.x"), equalTo(TEST_STRING)); + assertThat(result, equalTo("commaKey")); } } From 2926a2808adebd1f3d697a6959a57cbfa98b9dc8 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 03:35:06 +0200 Subject: [PATCH 11/20] Added `Unchecked.getByPath` and `Unchecked.getByPaths`. --- CHANGELOG.md | 3 + .../java/org/morphix/reflection/Fields.java | 59 +++++++++++++-- .../reflection/FieldsSafeGetByPathTest.java | 6 +- .../reflection/FieldsSafeGetByPathsTest.java | 10 ++- .../FieldsUncheckedGetByPathTest.java | 54 +++++++++++++ .../FieldsUncheckedGetByPathsTest.java | 75 +++++++++++++++++++ 6 files changed, 199 insertions(+), 8 deletions(-) create mode 100644 src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java create mode 100644 src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d3726ca..caaaa15c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ - Added `FieldPaths` for JSON Path-style field path parsing and resolution (properties, indices, and map keys). - Changed `Fields.Safe.getByPath` to resolve JSON Path-style expressions including array, list, and map selectors. - Changed `Fields.Safe.getByPaths(Object, String)` to split alternate paths on commas outside bracket segments. +- Added `Fields.Unchecked.getByPath(Object, String)` for path lookup without argument validation. +- Added `Fields.Unchecked.getByPaths(Object, String)` for comma-separated path lookup without argument validation. +- Added `Fields.Unchecked.getByPaths(Object, String...)` for ordered path lookup without argument validation. --- diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index 3168ea76..677131f2 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -835,7 +835,7 @@ static U getByPaths(final T obj, final String... paths) { */ static U getByPaths(final T obj, final String paths) { Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); - return FieldPaths.resolveValues(obj, paths); + return Unchecked.getByPaths(obj, paths); } /** @@ -857,10 +857,7 @@ static U getByPaths(final T obj, final String paths) { */ static U getByPath(final T obj, final String path) { Reflection.requireNotNull(path, "Cannot resolve field path: path is null"); - if (null == obj) { - return null; - } - return FieldPaths.resolveValue(obj, path); + return Unchecked.getByPath(obj, path); } } @@ -870,6 +867,7 @@ static U getByPath(final T obj, final String path) { * @author Radu Sebastian LAZIN */ interface Unsafe { + /** * Sets the field value using the {@link TheUnsafe} utility. *

@@ -909,6 +907,8 @@ static void set(final Object obj, final Field field, final Object value) { * This interface also exposes unchecked field lookup and enumeration helpers used by {@link Safe} and * {@link IgnoreAccess} so validation is not applied twice. Callers must supply valid arguments and handle * {@link ReflectionException} and other runtime failures; prefer {@link IgnoreAccess} in application code. + *

+ * Path lookup methods return {@code null} for a null root or path; the varargs form requires a non-null array. * * @author Radu Sebastian LAZIN */ @@ -1160,6 +1160,55 @@ static void set(final Object obj, final Field field, final T value) { } }); } + + /** + * Returns the first non-null value from the given paths without validating the arguments. + * + * @param object type + * @param field value type + * + * @param obj object to search + * @param paths paths to try in order + * @return first non-null value, or null if no path resolves + * @throws NullPointerException if the paths array is null + */ + static U getByPaths(final T obj, final String... paths) { + for (String path : paths) { + U result = getByPath(obj, path); + if (null != result) { + return result; + } + } + return null; + } + + /** + * Returns the first non-null value from comma-separated paths without validating the arguments. + * + * @param object type + * @param field value type + * + * @param obj object to search + * @param paths comma-separated paths + * @return first non-null value, or null if the root or paths are null or no path resolves + */ + static U getByPaths(final T obj, final String paths) { + return FieldPaths.resolveValues(obj, paths); + } + + /** + * Returns the value at a single path without validating the arguments. + * + * @param object type + * @param field value type + * + * @param obj object to search + * @param path path to resolve + * @return value, or null if the root or path is null or the path cannot be resolved + */ + static U getByPath(final T obj, final String path) { + return FieldPaths.resolveValue(obj, path); + } } /** diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index fb3e50a2..1da3d415 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -170,7 +170,8 @@ void shouldResolveRootContainer(final Object root, final String path, final Obje private static Stream rootPaths() { return Stream.of( Arguments.of(List.of(new Person("Alice")), "[0].name", "Alice"), - Arguments.of(Map.of("name", "Alice"), "['name']", "Alice")); + Arguments.of(Map.of("name", "Alice"), "['name']", "Alice"), + Arguments.of(Map.of("a,b", "Alice"), "a,b", "Alice")); } @ParameterizedTest @@ -191,9 +192,12 @@ private static Stream rootPaths() { "persons[2147483648]", "persons[0]name", "persons[0].", + "persons[[0]]", "attributes['name]", "attributes['name'", + "attributes['unfinished\\", "attributes['name']name", + "attributes[a'b'c]", "attributes[unknown]", "missing.name", "missing[0]", diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index a2d47fee..15edcf7c 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -65,7 +65,12 @@ private static final class Data { "attributes['unknown,key'],person.name", "unknown , person.name", ".bad,attributes[],person.name", - "attributes['missing\\\\'].name,person.name" + "attributes['missing\\\\'].name,person.name", + "attributes[foo[bar]],person.name", + "attributes[foo['a,b']],person.name", + "attributes[a'b'c],person.name", + "person.name] [skip],person.name", + "person.name] [foo[bar]],person.name" }) void shouldResolveFirstNonNullPath(final String paths) { var result = Fields.Safe.getByPaths(data, paths); @@ -94,7 +99,8 @@ void shouldResolveFieldAtFirstLevel() { " , , ", "unknown", "missing.name", - "persons[100].name" + "persons[100].name", + "person.name] trailing" }) void shouldReturnNullWhenNoPathResolves(final String paths) { var result = Fields.Safe.getByPaths(data, paths); diff --git a/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java new file mode 100644 index 00000000..6fea20a9 --- /dev/null +++ b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.reflection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +import java.util.Map; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test class for {@link Fields.Unchecked#getByPath(Object, String)}. + * + * @author Radu Sebastian LAZIN + */ +class FieldsUncheckedGetByPathTest { + + @Test + void shouldResolvePath() { + var result = Fields.Unchecked.getByPath(Map.of("name", "Alice"), "name"); + + assertThat(result, equalTo("Alice")); + } + + @ParameterizedTest + @MethodSource("nullInputs") + void shouldReturnNullForNullInput(final Object root, final String path) { + var result = Fields.Unchecked.getByPath(root, path); + + assertThat(result, nullValue()); + } + + private static Stream nullInputs() { + return Stream.of( + Arguments.of((Object) null, "name"), + Arguments.of(Map.of("name", "Alice"), (String) null)); + } +} diff --git a/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java new file mode 100644 index 00000000..c52c796b --- /dev/null +++ b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.morphix.reflection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Map; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test class for {@link Fields.Unchecked#getByPaths(Object, String)} and + * {@link Fields.Unchecked#getByPaths(Object, String...)}. + * + * @author Radu Sebastian LAZIN + */ +class FieldsUncheckedGetByPathsTest { + + @Test + void shouldResolveFirstPathFromCommaSeparatedAlternatives() { + var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), "unknown,name"); + + assertThat(result, equalTo("Alice")); + } + + @ParameterizedTest + @MethodSource("nullInputs") + void shouldReturnNullForNullInput(final Object root, final String paths) { + var result = Fields.Unchecked.getByPaths(root, paths); + + assertThat(result, nullValue()); + } + + private static Stream nullInputs() { + return Stream.of( + Arguments.of((Object) null, "name"), + Arguments.of(Map.of("name", "Alice"), (String) null)); + } + + @Test + void shouldResolveFirstNonNullVarargsPath() { + var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), "unknown", null, "name"); + + assertThat(result, equalTo("Alice")); + } + + @Test + void shouldReturnNullForEmptyVarargs() { + var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), new String[] { }); + + assertThat(result, nullValue()); + } + + @Test + void shouldThrowForNullVarargsArray() { + assertThrows(NullPointerException.class, () -> Fields.Unchecked.getByPaths(Map.of("name", "Alice"), (String[]) null)); + } +} From d8186b34ea3b8a0b863ba3431c94f8cf399cd925 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 04:00:20 +0200 Subject: [PATCH 12/20] Streamline the `getByPath` and `getByPaths` methods. --- CHANGELOG.md | 2 + .../java/org/morphix/reflection/Fields.java | 100 +++++++++--------- .../FieldsIgnoreAccessGetByPathsTest.java | 55 ++++++++++ .../reflection/FieldsSafeGetByPathTest.java | 8 +- .../reflection/FieldsSafeGetByPathsTest.java | 29 +++-- 5 files changed, 130 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index caaaa15c..b7be339d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ - Added `Fields.Unchecked.getByPath(Object, String)` for path lookup without argument validation. - Added `Fields.Unchecked.getByPaths(Object, String)` for comma-separated path lookup without argument validation. - Added `Fields.Unchecked.getByPaths(Object, String...)` for ordered path lookup without argument validation. +- Changed `Fields.IgnoreAccess.getByPaths(Object, String...)` to reject null arrays and skip null path entries. +- Changed `Fields.Safe.getByPaths(Object, String...)` to return null for null arrays and skip null path entries. --- diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index 677131f2..082f31af 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -451,9 +451,11 @@ static void setStatic(final Class cls, final Field field, final U valu * @param obj object to search the field in * @param paths possible paths to the field * @return field value or null if the field is not found or the field value cannot be returned + * @throws ReflectionException if {@code paths} is null */ static U getByPaths(final T obj, final String... paths) { - return Safe.getByPaths(obj, paths); + Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); + return Unchecked.getByPaths(obj, paths); } /** @@ -468,7 +470,8 @@ static U getByPaths(final T obj, final String... paths) { * @return field value or null if the field is not found or the field value cannot be returned */ static U getByPaths(final T obj, final String paths) { - return Safe.getByPaths(obj, paths); + Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); + return Unchecked.getByPaths(obj, paths); } /** @@ -482,7 +485,8 @@ static U getByPaths(final T obj, final String paths) { * @return field value or null if the field is not found or the field value cannot be returned */ static U getByPath(final T obj, final String path) { - return Safe.getByPath(obj, path); + Reflection.requireNotNull(path, "Cannot resolve field path: path is null"); + return Unchecked.getByPath(obj, path); } } @@ -806,18 +810,12 @@ static T getStatic(final Field field) { * @param obj object to search the field in * @param paths possible paths to the field * @return field value or null if the field is not found in none of the given paths - * @throws ReflectionException if {@code paths} is null or a path is null */ static U getByPaths(final T obj, final String... paths) { - Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); - U result = null; - for (String path : paths) { - result = getByPath(obj, path); - if (null != result) { - break; - } + if (null == obj || null == paths) { + return null; } - return result; + return Unchecked.getByPaths(obj, paths); } /** @@ -831,10 +829,11 @@ static U getByPaths(final T obj, final String... paths) { * @param obj object to search the field in * @param paths comma separated possible paths to the field * @return field value or null if the field is not found in none of the given paths - * @throws ReflectionException if the paths are null */ static U getByPaths(final T obj, final String paths) { - Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); + if (null == obj || null == paths) { + return null; + } return Unchecked.getByPaths(obj, paths); } @@ -853,45 +852,12 @@ static U getByPaths(final T obj, final String paths) { * @param path path to the value * @return field or container value, or {@code null} if the path is empty, invalid, not found, or {@code obj} is * {@code null} - * @throws ReflectionException if {@code path} is null */ static U getByPath(final T obj, final String path) { - Reflection.requireNotNull(path, "Cannot resolve field path: path is null"); - return Unchecked.getByPath(obj, path); - } - } - - /** - * Unsafe utility methods. - * - * @author Radu Sebastian LAZIN - */ - interface Unsafe { - - /** - * Sets the field value using the {@link TheUnsafe} utility. - *

- * Primitive fields accept the same widening conversions as {@link Field#set(Object, Object)}. A reference field accepts - * {@code null} or a value that is an instance of the field type. This is the path used for {@code final} fields, so - * those fields accept the same values as non-final fields. - * - * @param obj object on which the represented field's value is to be set - * @param field field on which to set the value - * @param value value to be set on the field - * @throws IllegalArgumentException if {@code value} is not assignable to the field - */ - static void set(final Object obj, final Field field, final Object value) { - boolean isStatic = JavaModifier.STATIC.isPresentOn(field); - Object instance = isStatic ? TheUnsafe.staticFieldBase(field) : obj; - long offset = isStatic ? TheUnsafe.staticFieldOffset(field) : TheUnsafe.objectFieldOffset(field); - Class type = field.getType(); - if (type.isPrimitive()) { - TheUnsafe.putPrimitive(instance, offset, type, value); - } else if (null == value || type.isInstance(value)) { - TheUnsafe.putObject(instance, offset, value); - } else { - throw TheUnsafe.incompatibleValue(type, value); + if (null == obj || null == path) { + return null; } + return Unchecked.getByPath(obj, path); } } @@ -1211,6 +1177,40 @@ static U getByPath(final T obj, final String path) { } } + /** + * Unsafe utility methods. + * + * @author Radu Sebastian LAZIN + */ + interface Unsafe { + + /** + * Sets the field value using the {@link TheUnsafe} utility. + *

+ * Primitive fields accept the same widening conversions as {@link Field#set(Object, Object)}. A reference field accepts + * {@code null} or a value that is an instance of the field type. This is the path used for {@code final} fields, so + * those fields accept the same values as non-final fields. + * + * @param obj object on which the represented field's value is to be set + * @param field field on which to set the value + * @param value value to be set on the field + * @throws IllegalArgumentException if {@code value} is not assignable to the field + */ + static void set(final Object obj, final Field field, final Object value) { + boolean isStatic = JavaModifier.STATIC.isPresentOn(field); + Object instance = isStatic ? TheUnsafe.staticFieldBase(field) : obj; + long offset = isStatic ? TheUnsafe.staticFieldOffset(field) : TheUnsafe.objectFieldOffset(field); + Class type = field.getType(); + if (type.isPrimitive()) { + TheUnsafe.putPrimitive(instance, offset, type, value); + } else if (null == value || type.isInstance(value)) { + TheUnsafe.putObject(instance, offset, value); + } else { + throw TheUnsafe.incompatibleValue(type, value); + } + } + } + /** * Resets the given field to its default value after instantiation on the given object. * diff --git a/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java index 012f9170..84c92ffd 100644 --- a/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java @@ -15,6 +15,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; @@ -115,4 +116,58 @@ void shouldReturnNullForEmptySearch() { assertThat(result, nullValue()); } + + @Test + void shouldThrowWhenPathsArrayIsNull() { + B b = new B(); + + ReflectionException exception = assertThrows(ReflectionException.class, + () -> Fields.IgnoreAccess.getByPaths(b, (String[]) null)); + + assertThat(exception.getMessage(), equalTo("Cannot resolve field paths: paths are null")); + } + + @Test + void shouldThrowWhenCommaSeparatedPathsAreNull() { + B b = new B(); + + ReflectionException exception = assertThrows(ReflectionException.class, + () -> Fields.IgnoreAccess.getByPaths(b, (String) null)); + + assertThat(exception.getMessage(), equalTo("Cannot resolve field paths: paths are null")); + } + + @Test + void shouldThrowWhenSinglePathIsNull() { + B b = new B(); + + ReflectionException exception = assertThrows(ReflectionException.class, + () -> Fields.IgnoreAccess.getByPath(b, null)); + + assertThat(exception.getMessage(), equalTo("Cannot resolve field path: path is null")); + } + + @Test + void shouldSkipNullVarargsPath() { + A a = new A(); + a.x = TEST_STRING; + B b = new B(); + b.a = a; + + var result = Fields.IgnoreAccess.getByPaths(b, null, "a.x"); + + assertThat(result, equalTo(TEST_STRING)); + } + + @Test + void shouldResolveFirstNonNullVarargsPath() { + A a = new A(); + a.x = TEST_STRING; + B b = new B(); + b.a = a; + + var result = Fields.IgnoreAccess.getByPaths(b, "missing", "a.x"); + + assertThat(result, equalTo(TEST_STRING)); + } } diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 1da3d415..130aaa85 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -16,7 +16,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; import java.util.Map; @@ -86,9 +85,10 @@ void shouldReturnNullIfObjectIsNull() { } @Test - void shouldThrowWhenPathIsNull() { - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPath(new WithNestedField(), null)); - assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null")); + void shouldReturnNullWhenPathIsNull() { + var result = Fields.Safe.getByPath(new WithNestedField(), null); + + assertThat(result, nullValue()); } private record Person(String name) { diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 15edcf7c..1763afa1 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -15,7 +15,6 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; import java.util.Map; @@ -109,9 +108,10 @@ void shouldReturnNullWhenNoPathResolves(final String paths) { } @Test - void shouldThrowWhenCommaSeparatedPathsAreNull() { - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, (String) null)); - assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null")); + void shouldReturnNullWhenCommaSeparatedPathsAreNull() { + var result = Fields.Safe.getByPaths(data, (String) null); + + assertThat(result, nullValue()); } @Test @@ -122,15 +122,24 @@ void shouldReturnNullForEmptyVarargs() { } @Test - void shouldThrowWhenAPathIsNull() { - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, new String[] { null })); - assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null")); + void shouldSkipNullPathInVarargs() { + var result = Fields.Safe.getByPaths(data, null, "person.name"); + + assertThat(result, equalTo("Alice")); } @Test - void shouldThrowWhenPathsArrayIsNull() { - ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(data, (String[]) null)); - assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null")); + void shouldReturnNullWhenPathsArrayIsNull() { + var result = Fields.Safe.getByPaths(data, (String[]) null); + + assertThat(result, nullValue()); + } + + @Test + void shouldReturnNullWhenOnlyPathIsNull() { + var result = Fields.Safe.getByPaths(data, new String[] { null }); + + assertThat(result, nullValue()); } @ParameterizedTest From 488ee3a8d7c19f69d85373e40fc63b33430d30b5 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 04:24:55 +0200 Subject: [PATCH 13/20] Refactor `FieldPathParser`. --- .../convert/strategy/FinderPathStrategy.java | 2 +- .../morphix/reflection/FieldPathParser.java | 94 +++++++++++++++---- .../org/morphix/reflection/FieldPaths.java | 14 +-- .../java/org/morphix/reflection/Fields.java | 2 +- .../morphix/reflection/FieldPathsTest.java | 4 +- 5 files changed, 83 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 13fa1792..9615d392 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -49,6 +49,6 @@ public ExtendedField find(final T source, final List fields, * @return field object pair */ public static ExtendedField getConverterFieldByPathInHierarchy(final T obj, final String path) { - return FieldPaths.resolveField(obj, path); + return FieldPaths.resolveFirstField(obj, path); } } diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java index eb47a15e..ba76ad33 100644 --- a/src/main/java/org/morphix/reflection/FieldPathParser.java +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -15,35 +15,49 @@ import java.lang.reflect.Field; import java.util.Map; +import org.morphix.lang.JavaObjects; + /** * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting * the expression into strings. *

- * The parser handles both single paths and comma-separated alternatives. + * {@link Syntax} selects a single path or comma-separated alternatives, while {@link Target} selects whether the result + * is a value or a reflective field with its owner. * * @author Radu Sebastian LAZIN */ final class FieldPathParser { /** - * Selects how the parser interprets paths and what it returns. + * Controls how many paths the expression may contain. */ - enum Mode { + enum Syntax { /** - * Resolves one path to its value. + * Parses the entire expression as one path. */ - SINGLE_VALUE, + SINGLE_PATH, /** - * Resolves comma-separated paths to the first non-null value. + * Parses comma-separated paths and stops at the first non-null value or matching field. */ - ALTERNATIVE_VALUES, + ALTERNATIVE_PATHS + } + + /** + * Selects the kind of result produced by the parser. + */ + enum Target { /** - * Resolves comma-separated paths to the first non-static field and its owner, even if the field value is null. + * Returns the value found at a path. */ - ALTERNATIVE_FIELD + VALUE, + + /** + * Returns the final non-static field and its owner, even when the field value is null. + */ + FIELD } /** @@ -77,35 +91,75 @@ enum Mode { private boolean invalid; /** - * Creates a parser for the given expression and resolution mode. + * Creates a parser for the given expression, path syntax, and result target. * * @param paths path expression - * @param mode resolution mode + * @param syntax whether the expression contains one path or comma-separated alternatives + * @param target whether to resolve a value or a field with its owner */ - private FieldPathParser(final String paths, final Mode mode) { + private FieldPathParser(final String paths, final Syntax syntax, final Target target) { this.paths = paths; this.length = paths.length(); - this.alternatives = Mode.SINGLE_VALUE != mode; - this.findField = Mode.ALTERNATIVE_FIELD == mode; + this.alternatives = Syntax.ALTERNATIVE_PATHS == syntax; + this.findField = Target.FIELD == target; } /** - * Resolves an expression using the requested mode. + * Resolves an expression using the requested syntax and result target. * * @param root root object * @param paths path expression - * @param mode resolution mode - * @return resolved value or extended field, or null if the root is null, the expression is empty, or no path matches + * @param syntax whether the expression contains one path or comma-separated alternatives + * @param target whether to resolve a value or a field with its owner + * @return resolved value or extended field, or null if the root or expression is null, the expression is empty, or no + * path matches */ - static Object resolve(final Object root, final String paths, final Mode mode) { + static Object resolve(final Object root, final String paths, final Syntax syntax, final Target target) { if (null == root || null == paths || paths.isEmpty()) { return null; } - return new FieldPathParser(paths, mode).resolve(root); + return new FieldPathParser(paths, syntax, target).resolve(root); + } + + /** + * Resolves one path to its value. + * + * @param value type + * @param root root object + * @param path path to resolve + * @return value, or null if the path cannot be resolved + */ + static U resolveValue(final Object root, final String path) { + return JavaObjects.cast(FieldPathParser.resolve(root, path, Syntax.SINGLE_PATH, Target.VALUE)); + } + + /** + * Resolves comma-separated paths to the first non-null value. + * + * @param value type + * @param root root object + * @param paths alternative paths + * @return first non-null value, or null if no path resolves + */ + static U resolveFirstValue(final Object root, final String paths) { + return JavaObjects.cast(FieldPathParser.resolve(root, paths, Syntax.ALTERNATIVE_PATHS, Target.VALUE)); + } + + /** + * Resolves comma-separated paths to the first non-static field and its owner. A field may be returned even when its + * value is null. + * + * @param root root object + * @param paths alternative paths + * @return field and its owner, or {@link ExtendedField#EMPTY} if no path resolves to a field + */ + static ExtendedField resolveFirstField(final Object root, final String paths) { + ExtendedField field = JavaObjects.cast(FieldPathParser.resolve(root, paths, Syntax.ALTERNATIVE_PATHS, Target.FIELD)); + return null == field ? ExtendedField.EMPTY : field; } /** - * Resolves the expression according to the configured mode. + * Resolves the expression according to the configured syntax and target. * * @param root root object * @return resolved value or extended field, or null diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 2e5460ba..10032521 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -16,9 +16,6 @@ import java.util.List; import java.util.Map; -import org.morphix.lang.JavaObjects; -import org.morphix.reflection.FieldPathParser.Mode; - /** * Resolves field paths using dot notation for properties and bracket notation for array/list indices and map keys. * Multiple paths can be separated by commas outside bracket selectors. @@ -37,7 +34,7 @@ public interface FieldPaths { * @return value or null if the path cannot be resolved */ static U resolveValue(final Object root, final String path) { - return JavaObjects.cast(FieldPathParser.resolve(root, path, Mode.SINGLE_VALUE)); + return FieldPathParser.resolveValue(root, path); } /** @@ -49,8 +46,8 @@ static U resolveValue(final Object root, final String path) { * @param paths alternative field paths * @return first non-null value or null */ - static U resolveValues(final Object root, final String paths) { - return JavaObjects.cast(FieldPathParser.resolve(root, paths, Mode.ALTERNATIVE_VALUES)); + static U resolveFirstValue(final Object root, final String paths) { + return FieldPathParser.resolveFirstValue(root, paths); } /** @@ -62,9 +59,8 @@ static U resolveValues(final Object root, final String paths) { * @param paths alternative field paths * @return field and its owning object, or {@link ExtendedField#EMPTY} */ - static ExtendedField resolveField(final Object root, final String paths) { - ExtendedField field = JavaObjects.cast(FieldPathParser.resolve(root, paths, Mode.ALTERNATIVE_FIELD)); - return null == field ? ExtendedField.EMPTY : field; + static ExtendedField resolveFirstField(final Object root, final String paths) { + return FieldPathParser.resolveFirstField(root, paths); } /** diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index 082f31af..0c9d533d 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -1159,7 +1159,7 @@ static U getByPaths(final T obj, final String... paths) { * @return first non-null value, or null if the root or paths are null or no path resolves */ static U getByPaths(final T obj, final String paths) { - return FieldPaths.resolveValues(obj, paths); + return FieldPaths.resolveFirstValue(obj, paths); } /** diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 1cd0d35a..5e4945cd 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -95,7 +95,7 @@ void shouldReturnNullForInvalidOrUnresolvedSinglePath(final String path) { @ParameterizedTest @MethodSource("alternativePaths") void shouldResolveFirstMatchingAlternative(final String paths, final String expected) { - var result = FieldPaths.resolveValues(root, paths); + var result = FieldPaths.resolveFirstValue(root, paths); assertThat(result, equalTo(expected)); } @@ -122,7 +122,7 @@ private static Stream alternativePaths() { "data['unterminated,items[0].name" }) void shouldReturnNullWhenNoAlternativeMatches(final String paths) { - var result = FieldPaths.resolveValues(root, paths); + var result = FieldPaths.resolveFirstValue(root, paths); assertThat(result, nullValue()); } From 4dc10be85c1b5f972343652702e18217208483d3 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 17:03:43 +0200 Subject: [PATCH 14/20] Remove `FieldPaths.readIndex` and add corresponding generic methods. --- CHANGELOG.md | 39 +- .../java/org/morphix/lang/JavaArrays.java | 22 + .../java/org/morphix/lang/JavaObjects.java | 32 ++ .../org/morphix/lang/collections/Lists.java | 24 ++ .../morphix/reflection/FieldPathParser.java | 2 +- .../org/morphix/reflection/FieldPaths.java | 22 - .../java/org/morphix/lang/JavaArraysTest.java | 389 ++++++++++++------ .../org/morphix/lang/JavaObjectsTest.java | 159 ++++++- .../morphix/lang/collections/ListsTest.java | 55 +++ .../morphix/reflection/FieldPathsTest.java | 7 - 10 files changed, 559 insertions(+), 192 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7be339d..84f26c5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,19 @@ - Added `Fields.Unchecked.getByPath(Object, String)` for path lookup without argument validation. - Added `Fields.Unchecked.getByPaths(Object, String)` for comma-separated path lookup without argument validation. - Added `Fields.Unchecked.getByPaths(Object, String...)` for ordered path lookup without argument validation. -- Changed `Fields.IgnoreAccess.getByPaths(Object, String...)` to reject null arrays and skip null path entries. -- Changed `Fields.Safe.getByPaths(Object, String...)` to return null for null arrays and skip null path entries. +- Changed `Fields.IgnoreAccess.getByPaths(Object, String...)` to reject `null` arrays and skip `null` path entries. +- Changed `Fields.Safe.getByPaths(Object, String...)` to return `null` for `null` arrays and skip `null` path entries. +- Added `JavaObjects.getAt(Object, int)` to read a zero-based index from an array or list, returning `null` when the value cannot be read. +- Added `JavaArrays.safeGet(T[], int)` to return an array element at an index, or `null` when the array is `null` or the index is out of range. +- Added `Lists.safeGet(List, int)` to return a list element at an index, or `null` when the list is `null`, empty, or the index is out of range. --- `1.1.1` -- Kept `Fields.IgnoreAccess.get(Object, String)` throwing `ReflectionException` for null input while using unchecked lookup for valid input. -- Changed `Fields.Unchecked.getOneDeclaredInHierarchy(Class, String)` to throw `NullPointerException` for a null class. -- Changed `Methods.Unchecked.getOneDeclaredInHierarchy(String, Class, Class...)` to throw `NullPointerException` for a null class. +- Kept `Fields.IgnoreAccess.get(Object, String)` throwing `ReflectionException` for `null` input while using unchecked lookup for valid input. +- Changed `Fields.Unchecked.getOneDeclaredInHierarchy(Class, String)` to throw `NullPointerException` for a `null` class. +- Changed `Methods.Unchecked.getOneDeclaredInHierarchy(String, Class, Class...)` to throw `NullPointerException` for a `null` class. - Fixed `Fields.Safe.getByPath(Object, String)` returning a field value for paths ending in a dot. - Added `Fields.Unchecked.getOneDeclared(Class, String)` for direct field lookup without parameter validation. - Added `Fields.Unchecked.getOneDeclaredInHierarchy(Class, String)` for direct field lookup throughout a class hierarchy. @@ -27,15 +30,15 @@ - Added `Fields.Unchecked.getAllDeclaredInHierarchy(Class)` for direct hierarchy field retrieval without parameter validation. - Added `Fields.Unchecked.getAllDeclaredInHierarchy(Class, Predicate)` for direct filtered hierarchy field retrieval without parameter validation. - Added `Fields.Unchecked.forEachMatching(Field[], Predicate, Consumer)` to pass matching declared fields to a consumer without allocating a result list. -- Added `Fields.Safe.getAllDeclared(Class)` for null-safe retrieval of a class's declared fields. -- Added `Fields.Safe.getAllDeclared(Object)` for null-safe retrieval of declared fields from an object's class. -- Added `Fields.Safe.getAllDeclared(Class, Predicate)` for null-safe retrieval and filtering of declared fields. -- Added `Fields.Safe.getAllDeclared(Object, Predicate)` for null-safe retrieval and filtering of declared fields from an object's class. -- Added `Fields.Safe.filter(List, Predicate)` for null-safe filtering of a field list. -- Added `Fields.Safe.getAllDeclaredInHierarchy(Class)` for null-safe hierarchy field retrieval. -- Added `Fields.Safe.getAllDeclaredInHierarchy(Class, Predicate)` for null-safe filtered hierarchy field retrieval. -- Added `Fields.Safe.getAllDeclaredInHierarchy(Object)` for null-safe hierarchy field retrieval from an object's class. -- Added `Fields.Safe.getAllDeclaredInHierarchy(Object, Predicate)` for null-safe filtered hierarchy field retrieval from an object's class. +- Added `Fields.Safe.getAllDeclared(Class)` for `null`-safe retrieval of a class's declared fields. +- Added `Fields.Safe.getAllDeclared(Object)` for `null`-safe retrieval of declared fields from an object's class. +- Added `Fields.Safe.getAllDeclared(Class, Predicate)` for `null`-safe retrieval and filtering of declared fields. +- Added `Fields.Safe.getAllDeclared(Object, Predicate)` for `null`-safe retrieval and filtering of declared fields from an object's class. +- Added `Fields.Safe.filter(List, Predicate)` for `null`-safe filtering of a field list. +- Added `Fields.Safe.getAllDeclaredInHierarchy(Class)` for `null`-safe hierarchy field retrieval. +- Added `Fields.Safe.getAllDeclaredInHierarchy(Class, Predicate)` for `null`-safe filtered hierarchy field retrieval. +- Added `Fields.Safe.getAllDeclaredInHierarchy(Object)` for `null`-safe hierarchy field retrieval from an object's class. +- Added `Fields.Safe.getAllDeclaredInHierarchy(Object, Predicate)` for `null`-safe filtered hierarchy field retrieval from an object's class. - Added `Methods.Unchecked.getOneDeclared(String, Class, Class...)` for direct method lookup without parameter validation. - Added `Methods.Unchecked.getOneDeclaredInHierarchy(String, Class, Class...)` for direct method lookup throughout a class hierarchy. - Added `Methods.Unchecked.getAllDeclared(Class)` for direct retrieval of a class's declared methods. @@ -43,10 +46,10 @@ - Added `Methods.Unchecked.getAllDeclaredInHierarchy(Class)` for direct superclass-chain method retrieval without parameter validation. - Added `Methods.Unchecked.getAllDeclaredInHierarchy(Class, Predicate)` for direct filtered superclass-chain method retrieval without parameter validation. - Added `Methods.Unchecked.forEachMatching(Method[], Predicate, Consumer)` to pass matching declared methods to a consumer without allocating a result list. -- Added `Methods.Safe.getAllDeclared(Class)` for null-safe retrieval of a class's declared methods. -- Added `Methods.Safe.getAllDeclared(Class, Predicate)` for null-safe retrieval and filtering of declared methods. -- Added `Methods.Safe.getAllDeclaredInHierarchy(Class)` for null-safe superclass-chain method retrieval. -- Added `Methods.Safe.getAllDeclaredInHierarchy(Class, Predicate)` for null-safe filtered superclass-chain method retrieval. +- Added `Methods.Safe.getAllDeclared(Class)` for `null`-safe retrieval of a class's declared methods. +- Added `Methods.Safe.getAllDeclared(Class, Predicate)` for `null`-safe retrieval and filtering of declared methods. +- Added `Methods.Safe.getAllDeclaredInHierarchy(Class)` for `null`-safe superclass-chain method retrieval. +- Added `Methods.Safe.getAllDeclaredInHierarchy(Class, Predicate)` for `null`-safe filtered superclass-chain method retrieval. - Changed `Methods.getAllDeclared(Class, Predicate)` to return matching methods in declaration order. - Added `Classes.isArray(Class)` to check whether a class represents an array type. - Added `Classes.isNotArray(Class)` to check whether a class does not represent an array type. diff --git a/src/main/java/org/morphix/lang/JavaArrays.java b/src/main/java/org/morphix/lang/JavaArrays.java index 4776a013..38e87641 100644 --- a/src/main/java/org/morphix/lang/JavaArrays.java +++ b/src/main/java/org/morphix/lang/JavaArrays.java @@ -145,4 +145,26 @@ static T[] empty(final Class componentType) { } return JavaObjects.cast(Array.newInstance(componentType, 0)); } + + /** + * Returns the element at the given index, or {@code null} if the array is {@code null} or the index is out of range. + *

+ * Will not throw a {@link NullPointerException} when the array is {@code null}, or an + * {@link ArrayIndexOutOfBoundsException} when the index is out of range. + * + * @param the component type of the array + * + * @param array the array to read, may be {@code null} + * @param index zero-based element index + * @return the element at {@code index}, or {@code null} when the array is {@code null} or the index is out of range + */ + static T safeGet(final T[] array, final int index) { + if (null == array || index < 0) { + return null; + } + if (index >= array.length) { + return null; + } + return array[index]; + } } diff --git a/src/main/java/org/morphix/lang/JavaObjects.java b/src/main/java/org/morphix/lang/JavaObjects.java index 9f769a58..068566f3 100644 --- a/src/main/java/org/morphix/lang/JavaObjects.java +++ b/src/main/java/org/morphix/lang/JavaObjects.java @@ -14,10 +14,13 @@ import java.lang.reflect.Array; import java.util.Collection; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import org.morphix.lang.collections.Lists; +import org.morphix.reflection.Classes; import org.morphix.reflection.Constructors; /** @@ -93,4 +96,33 @@ public static boolean isNotEmpty(final Object o) { public static boolean notEquals(final Object o1, final Object o2) { return !Objects.equals(o1, o2); } + + /** + * Returns the element at a zero-based index in an array or {@link List}. + *

+ * Returns {@code null} when {@code obj} is {@code null}, is neither a list nor an array, or the index is negative or + * out of range. Primitive array elements are boxed. + * + * @param element type + * + * @param obj array or list to read, may be {@code null} + * @param index zero-based element index + * @return the element at {@code index}, or {@code null} when it cannot be read + */ + public static T getAt(final Object obj, final int index) { + if (null == obj || index < 0) { + return null; + } + if (obj instanceof List list) { + return cast(Lists.safeGet(list, index)); + } + if (Classes.isNotArray(obj.getClass())) { + return null; + } + int length = Array.getLength(obj); + if (length == 0 || index >= length) { + return null; + } + return cast(Array.get(obj, index)); + } } diff --git a/src/main/java/org/morphix/lang/collections/Lists.java b/src/main/java/org/morphix/lang/collections/Lists.java index 24cf42dc..5fa76516 100644 --- a/src/main/java/org/morphix/lang/collections/Lists.java +++ b/src/main/java/org/morphix/lang/collections/Lists.java @@ -188,6 +188,30 @@ static boolean isNotEmpty(final List list) { return !isEmpty(list); } + /** + * Returns the element at the given index, or {@code null} if the list is {@code null}, empty, or the index is out of + * range. + *

+ * Will not throw a {@link NullPointerException} when the list is {@code null}, or an {@link IndexOutOfBoundsException} + * when the index is out of range. + * + * @param element type + * + * @param list the list to read, may be {@code null} + * @param index zero-based element index + * @return the element at {@code index}, or {@code null} when the list is {@code null}, empty, or the index is out of + * range + */ + static T safeGet(final List list, final int index) { + if (isEmpty(list)) { + return null; + } + if (index < 0 || index >= list.size()) { + return null; + } + return list.get(index); + } + /** * Merges two sorted lists returning a new mutable sorted list. *