From 861b712335d73272da84873d71eec7fe59cbed85 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 01:23:45 +0200 Subject: [PATCH 01/19] JSON like syntax for field finder - part 1. --- .../convert/strategy/FinderPathStrategy.java | 6 + .../org/morphix/reflection/FieldPaths.java | 352 ++++++++++++++++++ .../morphix/reflection/FieldPathsTest.java | 131 +++++++ .../reflection/FieldsSafeGetByPathTest.java | 56 +++ .../reflection/FieldsSafeGetByPathsTest.java | 8 +- 5 files changed, 552 insertions(+), 1 deletion(-) 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/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 92116766..87d2cda2 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -13,8 +13,14 @@ package org.morphix.convert.strategy; 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.FieldPathParser; /** 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/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 dbad4c03..64f1111b 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -22,6 +22,10 @@ import java.util.TreeMap; import java.util.stream.Stream; +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.Arguments; @@ -55,6 +59,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(); @@ -226,4 +244,42 @@ void shouldReturnNullForInvalidOrUnresolvedPath(final String path) { assertNull(result); } + + @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 046db0e9..44f1d25b 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -20,6 +20,9 @@ import java.util.Map; import java.util.TreeMap; +import java.util.LinkedHashMap; +import java.util.Map; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -66,7 +69,8 @@ private static final class Data { "unknown , person.name", ".bad,attributes[],person.name", "attributes['missing\\\\'].name,person.name", - "attributes[foo[bar]],person.name", + + "attributes[foo[bar]],person.name", "attributes[foo['a,b']],person.name", "attributes[a'b'c],person.name", "person.name] [skip],person.name", @@ -76,6 +80,8 @@ void shouldResolveFirstNonNullPath(final String paths) { var result = Fields.Safe.getByPaths(data, paths); assertThat(result, equalTo("Alice")); + + public Map keyed = new LinkedHashMap<>(); } @Test From 5ec6872f343e16d880bee05a13695df8192f24d2 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 01:35:56 +0200 Subject: [PATCH 02/19] Share cursor-based field path parser and support comma-separated alternatives --- .../org/morphix/reflection/FieldPaths.java | 335 +++--------------- .../morphix/reflection/FieldPathsTest.java | 77 ++-- 2 files changed, 109 insertions(+), 303 deletions(-) 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/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 From ab7ab6dc44ef2ec3244a6d8a70e73135b65c569d Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 01:39:56 +0200 Subject: [PATCH 03/19] Formatting. --- src/main/java/org/morphix/reflection/FieldPaths.java | 6 +++--- 1 file changed, 3 insertions(+), 3 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 From b8d7941ed69445184198ee67a5a9283075ef00ed Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 01:58:58 +0200 Subject: [PATCH 04/19] Resolve map properties as keys instead of internal fields --- .../java/org/morphix/reflection/FieldPaths.java | 6 ++---- .../convert/strategy/FinderPathStrategyTest.java | 13 +++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) 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 77232eff..df027e19 100644 --- a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -210,6 +210,19 @@ void shouldResolveMapKeysInsteadOfInternalFields() { assertThat(Fields.Safe.getByPath(map, "threshold"), nullValue()); } + @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 5737ed3e997e62893757fb45c45ca4ad0c75c033 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 02:28:17 +0200 Subject: [PATCH 05/19] Refactor boolean parameters. --- .../java/org/morphix/reflection/FieldPaths.java | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) 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 927c7ef568edbb6c50f0e275efad60b29c2cfd29 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 03:15:34 +0200 Subject: [PATCH 06/19] More test coverage. --- .../morphix/reflection/FieldPathsTest.java | 209 +++++++++++------- 1 file changed, 129 insertions(+), 80 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()); } } From 61531cdddcae850eaf9cc24aa303441d68ee9549 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 20 Nov 2026 04:24:55 +0200 Subject: [PATCH 07/19] Refactor `FieldPathParser`. --- .../java/org/morphix/reflection/FieldPaths.java | 14 +++++--------- .../org/morphix/reflection/FieldPathsTest.java | 4 ++-- 2 files changed, 7 insertions(+), 11 deletions(-) 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/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 5c6c1867207568f8ed6536058314fb19ff175192 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 17:03:43 +0200 Subject: [PATCH 08/19] Remove `FieldPaths.readIndex` and add corresponding generic methods. --- .../org/morphix/reflection/FieldPaths.java | 22 ------------------- .../morphix/reflection/FieldPathsTest.java | 7 ------ 2 files changed, 29 deletions(-) diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 10032521..720e3b7e 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -12,8 +12,6 @@ */ package org.morphix.reflection; -import java.lang.reflect.Array; -import java.util.List; import java.util.Map; /** @@ -77,26 +75,6 @@ static Object readProperty(final Object obj, final String name) { return obj instanceof Map map ? map.get(name) : Fields.Safe.get(obj, name); } - /** - * Reads a zero-based array or list index. - * - * @param obj container - * @param index element index - * @return element or null - */ - static Object readIndex(final Object obj, final int index) { - if (null == obj || index < 0) { - return null; - } - if (obj instanceof List list) { - return index < list.size() ? list.get(index) : null; - } - if (obj.getClass().isArray()) { - return index < Array.getLength(obj) ? Array.get(obj, index) : null; - } - return null; - } - /** * Reads a string map key. * diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 5e4945cd..51c83a98 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -197,13 +197,6 @@ private static Stream invalidProperties() { Arguments.of(new WithContainers(), "")); } - @Test - void shouldReturnNullForNegativeIndex() { - var result = FieldPaths.readIndex(root.items, -1); - - assertThat(result, nullValue()); - } - @Test void shouldReturnNullForNullMapKey() { var result = FieldPaths.readMapKey(root.data, null); From 4b8549d86f696271408f36dc5c1f233edac710b4 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 17:21:58 +0200 Subject: [PATCH 09/19] Remove more methods from `FieldPaths`. --- .../org/morphix/reflection/FieldPaths.java | 39 --- .../reflection/FieldPathParserTest.java | 252 ++++++++++++++++++ .../morphix/reflection/FieldPathsTest.java | 158 +---------- 3 files changed, 255 insertions(+), 194 deletions(-) create mode 100644 src/test/java/org/morphix/reflection/FieldPathParserTest.java diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 720e3b7e..3f8df263 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -22,45 +22,6 @@ */ public interface FieldPaths { - /** - * Resolves a single path to its value. - * - * @param value type - * - * @param root root object - * @param path field path - * @return value or null if the path cannot be resolved - */ - static U resolveValue(final Object root, final String path) { - return FieldPathParser.resolveValue(root, path); - } - - /** - * Resolves the first non-null value in a comma-separated list of paths. Empty alternatives are ignored. - * - * @param value type - * - * @param root root object - * @param paths alternative field paths - * @return first non-null value or null - */ - static U resolveFirstValue(final Object root, final String paths) { - return FieldPathParser.resolveFirstValue(root, 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. - * - * @param root root object - * @param paths alternative field paths - * @return field and its owning object, or {@link ExtendedField#EMPTY} - */ - static ExtendedField resolveFirstField(final Object root, final String paths) { - return FieldPathParser.resolveFirstField(root, paths); - } - /** * Reads a property, treating maps as containers rather than reflective objects. * diff --git a/src/test/java/org/morphix/reflection/FieldPathParserTest.java b/src/test/java/org/morphix/reflection/FieldPathParserTest.java new file mode 100644 index 00000000..f0e11d8c --- /dev/null +++ b/src/test/java/org/morphix/reflection/FieldPathParserTest.java @@ -0,0 +1,252 @@ +/* + * 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.hamcrest.Matchers.sameInstance; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Nested; +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; + +/** + * Test class for {@link FieldPathParser}. + * + * @author Radu Sebastian LAZIN + */ +class FieldPathParserTest { + + public static class Entry { + + public static String staticName = "static"; + + public String name; + } + + public static class WithContainers { + + public Entry[] entries = { new Entry(), new Entry() }; + + public Entry nullEntry = new Entry(); + + public List items = new FastArrayList<>(new Entry[] { new Entry() }); + + public Map data = new LinkedHashMap<>(); + + public WithContainers() { + entries[0].name = "fromArray"; + entries[1].name = "second"; + nullEntry.name = null; + 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"); + } + } + + private final WithContainers root = new WithContainers(); + + @Nested + class ResolveValueTests { + + @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 = FieldPathParser.resolveValue(root, path); + + assertThat(path, result, nullValue()); + } + + @ParameterizedTest + @MethodSource("singlePaths") + void shouldResolveSinglePath(final String path, final String expected) { + var result = FieldPathParser.resolveValue(root, path); + + assertThat(result, equalTo(expected)); + } + + 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")); + } + + @ParameterizedTest + @MethodSource("rootPaths") + void shouldResolveRootContainer(final Object container, final String path, final Object expected) { + var result = FieldPathParser.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 shouldReturnNullForNullRoot() { + var result = FieldPathParser.resolveValue(null, "entries[0]"); + + assertThat(result, nullValue()); + } + + @Test + void shouldResolveTerminalListElement() { + var result = FieldPathParser.resolveValue(root, "items[0]"); + + assertThat(result, equalTo(root.items.get(0))); + } + } + + @Nested + class ResolveFirstValueTests { + + @ParameterizedTest + @MethodSource("alternativePaths") + void shouldResolveFirstMatchingAlternative(final String paths, final String expected) { + var result = FieldPathParser.resolveFirstValue(root, paths); + + assertThat(result, equalTo(expected)); + } + + 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")); + } + + @ParameterizedTest + @ValueSource( + strings = { + ", ,", + "data['unterminated,items[0].name" + }) + void shouldReturnNullWhenNoAlternativeMatches(final String paths) { + var result = FieldPathParser.resolveFirstValue(root, paths); + + assertThat(result, nullValue()); + } + } + + @Nested + class ResolveFirstFieldTests { + + @Test + void shouldResolveFirstMatchingField() { + ExtendedField field = FieldPathParser.resolveFirstField(root, + " , missing.name, items[9].name, entries[0].name "); + + assertThat(field.getObject(), equalTo(root.entries[0])); + assertThat(field.getName(), equalTo("name")); + assertThat(field.getFieldValue(), equalTo("fromArray")); + } + + @Test + void shouldResolveFieldWithNullValueWithoutEvaluatingNextAlternative() { + ExtendedField field = FieldPathParser.resolveFirstField(root, "nullEntry.name,entries[0].name"); + + assertThat(field.getObject(), equalTo(root.nullEntry)); + assertThat(field.getName(), equalTo("name")); + assertThat(field.getFieldValue(), nullValue()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + ", ,", + "missing.name,items[9].name", + "items[0]", + "data['key']", + "entries[0].staticName" + }) + void shouldReturnEmptyWhenNoAlternativeMatches(final String paths) { + ExtendedField field = FieldPathParser.resolveFirstField(root, paths); + + assertThat(field, sameInstance(ExtendedField.EMPTY)); + } + + @Test + void shouldReturnEmptyForNullRoot() { + ExtendedField field = FieldPathParser.resolveFirstField(null, "entries[0].name"); + + assertThat(field, sameInstance(ExtendedField.EMPTY)); + } + + @Test + void shouldReturnEmptyForNullPaths() { + ExtendedField field = FieldPathParser.resolveFirstField(root, null); + + assertThat(field, sameInstance(ExtendedField.EMPTY)); + } + } +} diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 51c83a98..0dd52c0f 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -13,11 +13,8 @@ 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 java.util.stream.Stream; @@ -25,8 +22,6 @@ 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; /** * Test class for {@link FieldPaths}. @@ -35,153 +30,6 @@ */ class FieldPathsTest { - public static class Entry { - - public String name; - } - - public static class WithContainers { - - public Entry[] entries = { new Entry(), new Entry() }; - - public List items = new FastArrayList<>(new Entry[] { new Entry() }); - - public Map data = new LinkedHashMap<>(); - - 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"); - } - } - - 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()); - } - - @ParameterizedTest - @MethodSource("alternativePaths") - void shouldResolveFirstMatchingAlternative(final String paths, final String expected) { - var result = FieldPaths.resolveFirstValue(root, paths); - - assertThat(result, equalTo(expected)); - } - - 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")); - } - - @ParameterizedTest - @ValueSource( - strings = { - ", ,", - "data['unterminated,items[0].name" - }) - void shouldReturnNullWhenNoAlternativeMatches(final String paths) { - var result = FieldPaths.resolveFirstValue(root, paths); - - assertThat(result, nullValue()); - } - - @ParameterizedTest - @MethodSource("singlePaths") - void shouldResolveSinglePath(final String path, final String expected) { - var result = FieldPaths.resolveValue(root, path); - - assertThat(result, equalTo(expected)); - } - - 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")); - } - - @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 shouldReturnNullForNullRoot() { - var result = FieldPaths.resolveValue(null, "entries[0]"); - - assertThat(result, nullValue()); - } - - @Test - void shouldResolveTerminalListElement() { - var result = FieldPaths.resolveValue(root, "items[0]"); - - assertThat(result, equalTo(root.items.get(0))); - } - @ParameterizedTest @MethodSource("invalidProperties") void shouldReturnNullForInvalidProperty(final Object obj, final String name) { @@ -193,13 +41,13 @@ void shouldReturnNullForInvalidProperty(final Object obj, final String name) { private static Stream invalidProperties() { return Stream.of( Arguments.of(null, "key"), - Arguments.of(new WithContainers(), null), - Arguments.of(new WithContainers(), "")); + Arguments.of(new Object(), null), + Arguments.of(new Object(), "")); } @Test void shouldReturnNullForNullMapKey() { - var result = FieldPaths.readMapKey(root.data, null); + var result = FieldPaths.readMapKey(Map.of("key", "value"), null); assertThat(result, nullValue()); } From 4f02e62203e2aa6177efbcf21de354b110afadb8 Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 17:47:08 +0200 Subject: [PATCH 10/19] Completely removed `FieldPaths`. --- .../org/morphix/reflection/FieldPaths.java | 52 ------------------ .../morphix/reflection/FieldPathsTest.java | 54 ------------------- 2 files changed, 106 deletions(-) delete mode 100644 src/main/java/org/morphix/reflection/FieldPaths.java delete mode 100644 src/test/java/org/morphix/reflection/FieldPathsTest.java diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java deleted file mode 100644 index 3f8df263..00000000 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.util.Map; - -/** - * 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 { - - /** - * Reads a property, treating maps as containers rather than reflective objects. - * - * @param obj owning object - * @param name property name - * @return value or null - */ - static Object readProperty(final Object obj, final String name) { - if (null == obj || null == name || name.isEmpty()) { - return null; - } - return obj instanceof Map map ? map.get(name) : Fields.Safe.get(obj, name); - } - - /** - * Reads a string map key. - * - * @param obj container - * @param key map key - * @return value or null - */ - static Object readMapKey(final Object obj, final String key) { - if (null != key && obj instanceof Map map) { - return map.get(key); - } - return null; - } -} diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java deleted file mode 100644 index 0dd52c0f..00000000 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.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 FieldPaths}. - * - * @author Radu Sebastian LAZIN - */ -class FieldPathsTest { - - @ParameterizedTest - @MethodSource("invalidProperties") - void shouldReturnNullForInvalidProperty(final Object obj, final String name) { - var result = FieldPaths.readProperty(obj, name); - - assertThat(result, nullValue()); - } - - private static Stream invalidProperties() { - return Stream.of( - Arguments.of(null, "key"), - Arguments.of(new Object(), null), - Arguments.of(new Object(), "")); - } - - @Test - void shouldReturnNullForNullMapKey() { - var result = FieldPaths.readMapKey(Map.of("key", "value"), null); - - assertThat(result, nullValue()); - } -} From 2a01832e78900ac91a403c90d8668ff238869aaa Mon Sep 17 00:00:00 2001 From: raduking Date: Fri, 20 Nov 2026 20:53:44 +0200 Subject: [PATCH 11/19] Fields path parsing is tested via other methods. --- .../reflection/FieldPathParserTest.java | 252 ------------------ 1 file changed, 252 deletions(-) delete mode 100644 src/test/java/org/morphix/reflection/FieldPathParserTest.java diff --git a/src/test/java/org/morphix/reflection/FieldPathParserTest.java b/src/test/java/org/morphix/reflection/FieldPathParserTest.java deleted file mode 100644 index f0e11d8c..00000000 --- a/src/test/java/org/morphix/reflection/FieldPathParserTest.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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.hamcrest.Matchers.sameInstance; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import org.junit.jupiter.api.Nested; -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; - -/** - * Test class for {@link FieldPathParser}. - * - * @author Radu Sebastian LAZIN - */ -class FieldPathParserTest { - - public static class Entry { - - public static String staticName = "static"; - - public String name; - } - - public static class WithContainers { - - public Entry[] entries = { new Entry(), new Entry() }; - - public Entry nullEntry = new Entry(); - - public List items = new FastArrayList<>(new Entry[] { new Entry() }); - - public Map data = new LinkedHashMap<>(); - - public WithContainers() { - entries[0].name = "fromArray"; - entries[1].name = "second"; - nullEntry.name = null; - 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"); - } - } - - private final WithContainers root = new WithContainers(); - - @Nested - class ResolveValueTests { - - @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 = FieldPathParser.resolveValue(root, path); - - assertThat(path, result, nullValue()); - } - - @ParameterizedTest - @MethodSource("singlePaths") - void shouldResolveSinglePath(final String path, final String expected) { - var result = FieldPathParser.resolveValue(root, path); - - assertThat(result, equalTo(expected)); - } - - 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")); - } - - @ParameterizedTest - @MethodSource("rootPaths") - void shouldResolveRootContainer(final Object container, final String path, final Object expected) { - var result = FieldPathParser.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 shouldReturnNullForNullRoot() { - var result = FieldPathParser.resolveValue(null, "entries[0]"); - - assertThat(result, nullValue()); - } - - @Test - void shouldResolveTerminalListElement() { - var result = FieldPathParser.resolveValue(root, "items[0]"); - - assertThat(result, equalTo(root.items.get(0))); - } - } - - @Nested - class ResolveFirstValueTests { - - @ParameterizedTest - @MethodSource("alternativePaths") - void shouldResolveFirstMatchingAlternative(final String paths, final String expected) { - var result = FieldPathParser.resolveFirstValue(root, paths); - - assertThat(result, equalTo(expected)); - } - - 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")); - } - - @ParameterizedTest - @ValueSource( - strings = { - ", ,", - "data['unterminated,items[0].name" - }) - void shouldReturnNullWhenNoAlternativeMatches(final String paths) { - var result = FieldPathParser.resolveFirstValue(root, paths); - - assertThat(result, nullValue()); - } - } - - @Nested - class ResolveFirstFieldTests { - - @Test - void shouldResolveFirstMatchingField() { - ExtendedField field = FieldPathParser.resolveFirstField(root, - " , missing.name, items[9].name, entries[0].name "); - - assertThat(field.getObject(), equalTo(root.entries[0])); - assertThat(field.getName(), equalTo("name")); - assertThat(field.getFieldValue(), equalTo("fromArray")); - } - - @Test - void shouldResolveFieldWithNullValueWithoutEvaluatingNextAlternative() { - ExtendedField field = FieldPathParser.resolveFirstField(root, "nullEntry.name,entries[0].name"); - - assertThat(field.getObject(), equalTo(root.nullEntry)); - assertThat(field.getName(), equalTo("name")); - assertThat(field.getFieldValue(), nullValue()); - } - - @ParameterizedTest - @ValueSource( - strings = { - "", - ", ,", - "missing.name,items[9].name", - "items[0]", - "data['key']", - "entries[0].staticName" - }) - void shouldReturnEmptyWhenNoAlternativeMatches(final String paths) { - ExtendedField field = FieldPathParser.resolveFirstField(root, paths); - - assertThat(field, sameInstance(ExtendedField.EMPTY)); - } - - @Test - void shouldReturnEmptyForNullRoot() { - ExtendedField field = FieldPathParser.resolveFirstField(null, "entries[0].name"); - - assertThat(field, sameInstance(ExtendedField.EMPTY)); - } - - @Test - void shouldReturnEmptyForNullPaths() { - ExtendedField field = FieldPathParser.resolveFirstField(root, null); - - assertThat(field, sameInstance(ExtendedField.EMPTY)); - } - } -} From a26a480c2e4406d55243d3f71eb6337030ddc9a3 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Sun, 22 Nov 2026 03:49:10 +0200 Subject: [PATCH 12/19] Release `v1.1.3`. --- 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 0b6652e1..2e1df99a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Release Notes +`1.1.3` + +--- + `1.1.2` - Added `FieldPathParser` for JSON Path-style field path parsing and resolution (properties, indices, and map keys). diff --git a/README.md b/README.md index b91ab4af..3de9bb15 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.2` +Current release `1.1.3` ### Documentation @@ -88,6 +88,6 @@ Maven: add this dependency to your `pom.xml` io.github.raduking morphix-all - 1.1.2 + 1.1.3 ``` diff --git a/pom.xml b/pom.xml index 08cdd4ba..45fb83e0 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ io.github.raduking morphix-all - 1.1.2 + 1.1.3 jar ${project.groupId}:${project.artifactId} From 83db599c1f8ad431a39ec48192ce37c566fd76f1 Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 01:19:06 +0200 Subject: [PATCH 13/19] Added `ExtendedFields.valueNotNull`. --- CHANGELOG.md | 3 ++ pom.xml | 2 +- .../org/morphix/reflection/ExtendedField.java | 10 +++++ .../morphix/reflection/ExtendedFieldTest.java | 42 +++++++++++++++++-- .../reflection/ExtendedFieldsTest.java | 15 +++++++ 5 files changed, 67 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e1df99a..81b4439b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ `1.1.3` +- Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`. +- Upgraded parent to `4.1.3`. + --- `1.1.2` diff --git a/pom.xml b/pom.xml index 45fb83e0..4c2cdaff 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ org.springframework.boot spring-boot-starter-parent - 4.1.2 + 4.1.3 diff --git a/src/main/java/org/morphix/reflection/ExtendedField.java b/src/main/java/org/morphix/reflection/ExtendedField.java index ed9a85eb..7845ab84 100644 --- a/src/main/java/org/morphix/reflection/ExtendedField.java +++ b/src/main/java/org/morphix/reflection/ExtendedField.java @@ -373,6 +373,16 @@ public boolean typeMeets(final Predicate predicate) { return predicate.test(getType()); } + /** + * Returns true if the field value is not {@code null}, false otherwise. Can be used as a predicate in + * {@link ExtendedFields#findAllNonStatic(Object, Predicate)}. + * + * @return true if the field value is not {@code null}, false otherwise + */ + public boolean valueNotNull() { + return null != getFieldValue(); + } + /** * Returns true if the annotation is present on the extended field. * diff --git a/src/test/java/org/morphix/reflection/ExtendedFieldTest.java b/src/test/java/org/morphix/reflection/ExtendedFieldTest.java index 62959c81..67fed99e 100644 --- a/src/test/java/org/morphix/reflection/ExtendedFieldTest.java +++ b/src/test/java/org/morphix/reflection/ExtendedFieldTest.java @@ -14,6 +14,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -48,11 +50,11 @@ public static class A { } @Test - void shouldBuildStringWithToString() throws Exception { + void shouldBuildStringWithToString() { A a = new A(); a.l = TEST_LONG; - ExtendedField fop = ExtendedField.of(A.class.getDeclaredField("l"), a); + ExtendedField fop = ExtendedField.of(Fields.getOneDeclared(A.class, "l"), a); String result = fop.toString(); assertThat(result, equalTo("Field: l" + EOL @@ -73,11 +75,11 @@ void shouldBuildStringWithToStringWithNoField() { } @Test - void shouldBuildStringWithToStringWithNoObject() throws Exception { + void shouldBuildStringWithToStringWithNoObject() { A a = new A(); a.l = TEST_LONG; - ExtendedField fop = ExtendedField.of(A.class.getDeclaredField("l")); + ExtendedField fop = ExtendedField.of(Fields.getOneDeclared(A.class, "l")); String result = fop.toString(); assertThat(result, equalTo("Field: l" + EOL @@ -188,6 +190,38 @@ void shouldReturnAnnotationFromGetterMethod() { assertThat(annotation, equalTo(method.getAnnotation(Deprecated.class))); } + @Test + void shouldReturnTrueOnValueNotNullWhenFieldValueIsNotNull() { + A a = new A(); + a.l = TEST_LONG; + Field field = Fields.getOneDeclared(A.class, "l"); + ExtendedField ef = ExtendedField.of(field, a); + + boolean result = ef.valueNotNull(); + + assertTrue(result); + } + + @Test + void shouldReturnFalseOnValueNotNullWhenFieldValueIsNull() { + A a = new A(); + Field field = Fields.getOneDeclared(A.class, "l"); + ExtendedField ef = ExtendedField.of(field, a); + + boolean result = ef.valueNotNull(); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnValueNotNullWhenThereIsNoFieldOrObject() { + ExtendedField ef = ExtendedField.of(null); + + boolean result = ef.valueNotNull(); + + assertFalse(result); + } + @Test void shouldThrowExceptionWhenTryingToInstantiate() { UnsupportedOperationException e = Tests.verifyDefaultConstructorThrows(ExtendedField.Default.class); diff --git a/src/test/java/org/morphix/reflection/ExtendedFieldsTest.java b/src/test/java/org/morphix/reflection/ExtendedFieldsTest.java index afd30e2e..242e6c9f 100644 --- a/src/test/java/org/morphix/reflection/ExtendedFieldsTest.java +++ b/src/test/java/org/morphix/reflection/ExtendedFieldsTest.java @@ -38,6 +38,7 @@ class ExtendedFieldsTest { private static final String WITH_GETTER = "withGetter"; private static final String COMPUTED = "computed"; private static final String BOXED = "boxed"; + private static final String SET = "set"; private static final String ITEM = "item"; private static final String BASE_MAPPING = "baseMapping"; private static final String DERIVED_MAPPING = "derivedMapping"; @@ -156,6 +157,13 @@ void shouldNotReturnStaticGetterAsAProperty() { assertThat(ExtendedFields.findAllNonStatic(new WithOnlyStaticGetter()), equalTo(List.of())); } + @Test + void shouldReturnOnlyFieldsWithNotNullValueWhenUsingValueNotNullAsPredicate() { + List fields = ExtendedFields.findAllNonStatic(new WithNullableFields(), ExtendedField::valueNotNull); + + assertThat(namesOf(fields), contains(SET)); + } + private static List namesOf(final List fields) { return fields.stream().map(ExtendedField::getName).toList(); } @@ -280,6 +288,13 @@ public static Long getValue() { } } + public static class WithNullableFields { + + Long set = 1L; + + Long unset; + } + public static class WithOnlyStaticGetter { public static Long getValue() { From 380f9c78f44f37f7584d611c810faa3d89a0b04a Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 01:28:44 +0200 Subject: [PATCH 14/19] Added `JavaObjects.isArray`. --- CHANGELOG.md | 1 + .../java/org/morphix/lang/JavaObjects.java | 11 ++++ .../org/morphix/lang/JavaObjectsTest.java | 53 +++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81b4439b..5e07320e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ `1.1.3` - Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`. +- Added `JavaObjects.isArray(Object)` to check whether an object is an array, returning `false` for `null`. - Upgraded parent to `4.1.3`. --- diff --git a/src/main/java/org/morphix/lang/JavaObjects.java b/src/main/java/org/morphix/lang/JavaObjects.java index 068566f3..6205f701 100644 --- a/src/main/java/org/morphix/lang/JavaObjects.java +++ b/src/main/java/org/morphix/lang/JavaObjects.java @@ -125,4 +125,15 @@ public static T getAt(final Object obj, final int index) { } return cast(Array.get(obj, index)); } + + /** + * Returns true if the given object is an array, false otherwise. + * + * @param obj object to check + * @return true if the given object is an array, false otherwise + */ + public static boolean isArray(final Object obj) { + Class cls = Classes.getFrom(obj); + return Classes.isArray(cls); + } } diff --git a/src/test/java/org/morphix/lang/JavaObjectsTest.java b/src/test/java/org/morphix/lang/JavaObjectsTest.java index 529890ae..695d5973 100644 --- a/src/test/java/org/morphix/lang/JavaObjectsTest.java +++ b/src/test/java/org/morphix/lang/JavaObjectsTest.java @@ -343,6 +343,59 @@ void shouldReturnTrueWhenOneObjectIsNull() { } } + @Nested + class IsArrayTests { + + @Test + void shouldReturnFalseOnNull() { + boolean result = JavaObjects.isArray(null); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnNonArray() { + boolean result = JavaObjects.isArray(BUBU); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnList() { + boolean result = JavaObjects.isArray(List.of(BUBU)); + + assertFalse(result); + } + + @Test + void shouldReturnTrueOnObjectArray() { + boolean result = JavaObjects.isArray(new String[] { BUBU }); + + assertTrue(result); + } + + @Test + void shouldReturnTrueOnEmptyArray() { + boolean result = JavaObjects.isArray(new Object[] { }); + + assertTrue(result); + } + + @Test + void shouldReturnTrueOnPrimitiveArray() { + boolean result = JavaObjects.isArray(new int[] { 1 }); + + assertTrue(result); + } + + @Test + void shouldReturnTrueOnMultiDimensionalArray() { + boolean result = JavaObjects.isArray(new int[][] { { 1 } }); + + assertTrue(result); + } + } + @Nested class GetAtTests { From 91b9506bf4a1a05fcbcd13291b6647cd43a5527a Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 01:30:32 +0200 Subject: [PATCH 15/19] Added `JavaObjects.isNotArray`. --- CHANGELOG.md | 1 + .../java/org/morphix/lang/JavaObjects.java | 10 ++++ .../org/morphix/lang/JavaObjectsTest.java | 53 +++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e07320e..11a1a74e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`. - Added `JavaObjects.isArray(Object)` to check whether an object is an array, returning `false` for `null`. +- Added `JavaObjects.isNotArray(Object)` to check whether an object is not an array, returning `true` for `null`. - Upgraded parent to `4.1.3`. --- diff --git a/src/main/java/org/morphix/lang/JavaObjects.java b/src/main/java/org/morphix/lang/JavaObjects.java index 6205f701..0e71e34e 100644 --- a/src/main/java/org/morphix/lang/JavaObjects.java +++ b/src/main/java/org/morphix/lang/JavaObjects.java @@ -136,4 +136,14 @@ public static boolean isArray(final Object obj) { Class cls = Classes.getFrom(obj); return Classes.isArray(cls); } + + /** + * Returns true if the given object is not an array, false otherwise. + * + * @param obj object to check + * @return true if the given object is not an array, false otherwise + */ + public static boolean isNotArray(final Object obj) { + return !isArray(obj); + } } diff --git a/src/test/java/org/morphix/lang/JavaObjectsTest.java b/src/test/java/org/morphix/lang/JavaObjectsTest.java index 695d5973..daa7e473 100644 --- a/src/test/java/org/morphix/lang/JavaObjectsTest.java +++ b/src/test/java/org/morphix/lang/JavaObjectsTest.java @@ -396,6 +396,59 @@ void shouldReturnTrueOnMultiDimensionalArray() { } } + @Nested + class IsNotArrayTests { + + @Test + void shouldReturnTrueOnNull() { + boolean result = JavaObjects.isNotArray(null); + + assertTrue(result); + } + + @Test + void shouldReturnTrueOnNonArray() { + boolean result = JavaObjects.isNotArray(BUBU); + + assertTrue(result); + } + + @Test + void shouldReturnTrueOnList() { + boolean result = JavaObjects.isNotArray(List.of(BUBU)); + + assertTrue(result); + } + + @Test + void shouldReturnFalseOnObjectArray() { + boolean result = JavaObjects.isNotArray(new String[] { BUBU }); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnEmptyArray() { + boolean result = JavaObjects.isNotArray(new Object[] { }); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnPrimitiveArray() { + boolean result = JavaObjects.isNotArray(new int[] { 1 }); + + assertFalse(result); + } + + @Test + void shouldReturnFalseOnMultiDimensionalArray() { + boolean result = JavaObjects.isNotArray(new int[][] { { 1 } }); + + assertFalse(result); + } + } + @Nested class GetAtTests { From a61d2e57e64760ad4eaa52ac06f3fd08089d701a Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 01:35:04 +0200 Subject: [PATCH 16/19] Small refactor. --- src/test/java/org/morphix/reflection/ExtendedFieldTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/morphix/reflection/ExtendedFieldTest.java b/src/test/java/org/morphix/reflection/ExtendedFieldTest.java index 67fed99e..264204da 100644 --- a/src/test/java/org/morphix/reflection/ExtendedFieldTest.java +++ b/src/test/java/org/morphix/reflection/ExtendedFieldTest.java @@ -54,7 +54,8 @@ void shouldBuildStringWithToString() { A a = new A(); a.l = TEST_LONG; - ExtendedField fop = ExtendedField.of(Fields.getOneDeclared(A.class, "l"), a); + Field field = Fields.getOneDeclared(A.class, "l"); + ExtendedField fop = ExtendedField.of(field, a); String result = fop.toString(); assertThat(result, equalTo("Field: l" + EOL @@ -79,7 +80,8 @@ void shouldBuildStringWithToStringWithNoObject() { A a = new A(); a.l = TEST_LONG; - ExtendedField fop = ExtendedField.of(Fields.getOneDeclared(A.class, "l")); + Field field = Fields.getOneDeclared(A.class, "l"); + ExtendedField fop = ExtendedField.of(field); String result = fop.toString(); assertThat(result, equalTo("Field: l" + EOL From 90a6a47d77bf3e35d8d07a5d71176b583337204d Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 02:00:38 +0200 Subject: [PATCH 17/19] Use `isArray`. --- src/main/java/org/morphix/lang/JavaObjects.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/morphix/lang/JavaObjects.java b/src/main/java/org/morphix/lang/JavaObjects.java index 0e71e34e..b1a3dc0f 100644 --- a/src/main/java/org/morphix/lang/JavaObjects.java +++ b/src/main/java/org/morphix/lang/JavaObjects.java @@ -69,7 +69,7 @@ public static boolean isEmpty(final Object o) { case Collection collection -> collection.isEmpty(); case Map map -> map.isEmpty(); case Optional optional -> optional.isEmpty(); - case Object object when object.getClass().isArray() -> Array.getLength(o) == 0; + case Object object when isArray(object) -> Array.getLength(o) == 0; default -> false; }; } From aa19fb96d722b07fd0dd3f62849a4d7c14fe3c90 Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 03:16:31 +0200 Subject: [PATCH 18/19] Rebased with master. --- .../convert/strategy/FinderPathStrategy.java | 6 ------ .../convert/strategy/FinderPathStrategyTest.java | 13 ------------- .../morphix/reflection/FieldsSafeGetByPathTest.java | 6 ++---- .../reflection/FieldsSafeGetByPathsTest.java | 8 +------- 4 files changed, 3 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 87d2cda2..92116766 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -13,14 +13,8 @@ package org.morphix.convert.strategy; 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.FieldPathParser; /** diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java index df027e19..77232eff 100644 --- a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -210,19 +210,6 @@ void shouldResolveMapKeysInsteadOfInternalFields() { assertThat(Fields.Safe.getByPath(map, "threshold"), nullValue()); } - @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")); diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 64f1111b..ee93d23f 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -17,20 +17,18 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertNull; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Stream; -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.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)}. diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 44f1d25b..046db0e9 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -20,9 +20,6 @@ import java.util.Map; import java.util.TreeMap; -import java.util.LinkedHashMap; -import java.util.Map; - import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -69,8 +66,7 @@ private static final class Data { "unknown , person.name", ".bad,attributes[],person.name", "attributes['missing\\\\'].name,person.name", - - "attributes[foo[bar]],person.name", + "attributes[foo[bar]],person.name", "attributes[foo['a,b']],person.name", "attributes[a'b'c],person.name", "person.name] [skip],person.name", @@ -80,8 +76,6 @@ void shouldResolveFirstNonNullPath(final String paths) { var result = Fields.Safe.getByPaths(data, paths); assertThat(result, equalTo("Alice")); - - public Map keyed = new LinkedHashMap<>(); } @Test From 039748d3d61751addd503c75aaa462668d12d4a2 Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 03:22:53 +0200 Subject: [PATCH 19/19] Fix wrong rebase. --- .../reflection/FieldsSafeGetByPathTest.java | 54 ------------------- 1 file changed, 54 deletions(-) diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index ee93d23f..dbad4c03 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -17,7 +17,6 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertNull; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -28,7 +27,6 @@ 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)}. @@ -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(); @@ -242,42 +226,4 @@ void shouldReturnNullForInvalidOrUnresolvedPath(final String path) { assertNull(result); } - - @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; - } }