componentType) {
}
return JavaObjects.cast(Array.newInstance(componentType, 0));
}
+
+ /**
+ * Returns the element at the given index, or {@code null} if the array is {@code null} or the index is out of range.
+ *
+ * Will not throw a {@link NullPointerException} when the array is {@code null}, or an
+ * {@link ArrayIndexOutOfBoundsException} when the index is out of range.
+ *
+ * @param the component type of the array
+ *
+ * @param array the array to read, may be {@code null}
+ * @param index zero-based element index
+ * @return the element at {@code index}, or {@code null} when the array is {@code null} or the index is out of range
+ */
+ static T safeGet(final T[] array, final int index) {
+ if (null == array || index < 0) {
+ return null;
+ }
+ if (index >= array.length) {
+ return null;
+ }
+ return array[index];
+ }
}
diff --git a/src/main/java/org/morphix/lang/JavaObjects.java b/src/main/java/org/morphix/lang/JavaObjects.java
index 9f769a58..068566f3 100644
--- a/src/main/java/org/morphix/lang/JavaObjects.java
+++ b/src/main/java/org/morphix/lang/JavaObjects.java
@@ -14,10 +14,13 @@
import java.lang.reflect.Array;
import java.util.Collection;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import org.morphix.lang.collections.Lists;
+import org.morphix.reflection.Classes;
import org.morphix.reflection.Constructors;
/**
@@ -93,4 +96,33 @@ public static boolean isNotEmpty(final Object o) {
public static boolean notEquals(final Object o1, final Object o2) {
return !Objects.equals(o1, o2);
}
+
+ /**
+ * Returns the element at a zero-based index in an array or {@link List}.
+ *
+ * Returns {@code null} when {@code obj} is {@code null}, is neither a list nor an array, or the index is negative or
+ * out of range. Primitive array elements are boxed.
+ *
+ * @param element type
+ *
+ * @param obj array or list to read, may be {@code null}
+ * @param index zero-based element index
+ * @return the element at {@code index}, or {@code null} when it cannot be read
+ */
+ public static T getAt(final Object obj, final int index) {
+ if (null == obj || index < 0) {
+ return null;
+ }
+ if (obj instanceof List> list) {
+ return cast(Lists.safeGet(list, index));
+ }
+ if (Classes.isNotArray(obj.getClass())) {
+ return null;
+ }
+ int length = Array.getLength(obj);
+ if (length == 0 || index >= length) {
+ return null;
+ }
+ return cast(Array.get(obj, index));
+ }
}
diff --git a/src/main/java/org/morphix/lang/collections/Lists.java b/src/main/java/org/morphix/lang/collections/Lists.java
index 24cf42dc..5fa76516 100644
--- a/src/main/java/org/morphix/lang/collections/Lists.java
+++ b/src/main/java/org/morphix/lang/collections/Lists.java
@@ -188,6 +188,30 @@ static boolean isNotEmpty(final List list) {
return !isEmpty(list);
}
+ /**
+ * Returns the element at the given index, or {@code null} if the list is {@code null}, empty, or the index is out of
+ * range.
+ *
+ * Will not throw a {@link NullPointerException} when the list is {@code null}, or an {@link IndexOutOfBoundsException}
+ * when the index is out of range.
+ *
+ * @param element type
+ *
+ * @param list the list to read, may be {@code null}
+ * @param index zero-based element index
+ * @return the element at {@code index}, or {@code null} when the list is {@code null}, empty, or the index is out of
+ * range
+ */
+ static T safeGet(final List list, final int index) {
+ if (isEmpty(list)) {
+ return null;
+ }
+ if (index < 0 || index >= list.size()) {
+ return null;
+ }
+ return list.get(index);
+ }
+
/**
* Merges two sorted lists returning a new mutable sorted list.
*
diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java
new file mode 100644
index 00000000..3f3783fd
--- /dev/null
+++ b/src/main/java/org/morphix/reflection/FieldPathParser.java
@@ -0,0 +1,558 @@
+/*
+ * 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.Field;
+import java.util.Map;
+
+import org.morphix.lang.JavaObjects;
+
+/**
+ * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting
+ * the expression into strings.
+ *
+ * {@link Syntax} selects a single path or comma-separated alternatives, while {@link Target} selects whether the result
+ * is a value or a reflective field with its owner.
+ *
+ * @author Radu Sebastian LAZIN
+ */
+public final class FieldPathParser {
+
+ /**
+ * Controls how many paths the expression may contain.
+ */
+ private enum Syntax {
+
+ /**
+ * Parses the entire expression as one path.
+ */
+ SINGLE_PATH,
+
+ /**
+ * Parses comma-separated paths and stops at the first non-null value or matching field.
+ */
+ ALTERNATIVE_PATHS
+ }
+
+ /**
+ * Selects the kind of result produced by the parser.
+ */
+ private enum Target {
+
+ /**
+ * Returns the value found at a path.
+ */
+ VALUE,
+
+ /**
+ * Returns the final non-static field and its owner, even when the field value is null.
+ */
+ FIELD
+ }
+
+ /**
+ * Path expression being parsed.
+ */
+ private final String paths;
+
+ /**
+ * Length of the path expression.
+ */
+ private final int length;
+
+ /**
+ * Whether comma-separated alternative paths are accepted.
+ */
+ private final boolean alternatives;
+
+ /**
+ * Whether the result must be a reflective field and its owning object.
+ */
+ private final boolean findField;
+
+ /**
+ * Index of the next character to read from {@link #paths}.
+ */
+ private int index;
+
+ /**
+ * Whether the current alternative contains invalid syntax.
+ */
+ private boolean invalid;
+
+ /**
+ * Creates a parser for the given expression, path syntax, and result target.
+ *
+ * @param paths path expression
+ * @param syntax whether the expression contains one path or comma-separated alternatives
+ * @param target whether to resolve a value or a field with its owner
+ */
+ private FieldPathParser(final String paths, final Syntax syntax, final Target target) {
+ this.paths = paths;
+ this.length = paths.length();
+ this.alternatives = Syntax.ALTERNATIVE_PATHS == syntax;
+ this.findField = Target.FIELD == target;
+ }
+
+ /**
+ * Resolves one path to its value.
+ *
+ * @param value type
+ *
+ * @param root root object
+ * @param path path to resolve
+ * @return value, or null if the path cannot be resolved
+ */
+ public static U resolveValue(final Object root, final String path) {
+ return resolve(root, path, Syntax.SINGLE_PATH, Target.VALUE);
+ }
+
+ /**
+ * Resolves comma-separated paths to the first non-null value.
+ *
+ * @param value type
+ *
+ * @param root root object
+ * @param paths alternative paths
+ * @return first non-null value, or null if no path resolves
+ */
+ public static U resolveFirstValue(final Object root, final String paths) {
+ return resolve(root, paths, Syntax.ALTERNATIVE_PATHS, Target.VALUE);
+ }
+
+ /**
+ * Resolves comma-separated paths to the first non-static field and its owner. A field may be returned even when its
+ * value is null.
+ *
+ * @param root root object
+ * @param paths alternative paths
+ * @return field and its owner, or {@link ExtendedField#EMPTY} if no path resolves to a field
+ */
+ public static ExtendedField resolveFirstField(final Object root, final String paths) {
+ ExtendedField field = resolve(root, paths, Syntax.ALTERNATIVE_PATHS, Target.FIELD);
+ return null == field ? ExtendedField.EMPTY : field;
+ }
+
+ /**
+ * Resolves an expression using the requested syntax and result target.
+ *
+ * @param result type
+ *
+ * @param root root object
+ * @param paths path expression
+ * @param syntax whether the expression contains one path or comma-separated alternatives
+ * @param target whether to resolve a value or a field with its owner
+ * @return resolved value or extended field, or null if the root or expression is null, the expression is empty, or no
+ * path matches
+ */
+ private static U resolve(final Object root, final String paths, final Syntax syntax, final Target target) {
+ if (null == root || null == paths || paths.isEmpty()) {
+ return null;
+ }
+ FieldPathParser parser = new FieldPathParser(paths, syntax, target);
+ return JavaObjects.cast(parser.resolve(root));
+ }
+
+ /**
+ * Resolves the expression according to the configured syntax and target.
+ *
+ * @param root root object
+ * @return resolved value or extended field, or null
+ */
+ private Object resolve(final Object root) {
+ return alternatives ? resolveAlternatives(root) : resolveSinglePath(root);
+ }
+
+ /**
+ * Resolves one path, requiring the entire expression to be valid.
+ *
+ * @param root root object
+ * @return resolved value, or null if the path is invalid or cannot be resolved
+ */
+ private Object resolveSinglePath(final Object root) {
+ Object result = readPath(root);
+ return !invalid && index == length ? result : null;
+ }
+
+ /**
+ * Resolves paths in order, stopping at the first match. A malformed alternative can be skipped if its end is
+ * unambiguous. An unterminated bracket or quoted selector consumes the remainder of the expression.
+ *
+ * @param root root object
+ * @return resolved value or extended field, or null if no alternative matches
+ */
+ private Object resolveAlternatives(final Object root) {
+ while (index < length) {
+ skipWhitespace();
+ if (consume(',')) {
+ continue;
+ }
+ if (index == length) {
+ return null;
+ }
+ invalid = false;
+ Object result = readPath(root);
+ skipWhitespace();
+ if (index < length && ',' != paths.charAt(index)) {
+ invalid = true;
+ skipInvalidPath();
+ }
+ if (!invalid && null != result) {
+ return result;
+ }
+ consume(',');
+ }
+ return null;
+ }
+
+ /**
+ * Reads one path, resolving each property or bracket selector as it is consumed.
+ *
+ * @param root root object
+ * @return resolved value or extended field, or null if the path is invalid or cannot be resolved
+ */
+ private Object readPath(final Object root) {
+ Object value = root;
+ if ('[' != paths.charAt(index)) {
+ value = readProperty(value);
+ }
+ while (index < length && !invalid) {
+ if (consume('[')) {
+ value = readBracket(value);
+ } else if (consume('.')) {
+ value = readProperty(value);
+ } else {
+ break;
+ }
+ }
+ return invalid ? null : value;
+ }
+
+ /**
+ * Reads a property name and resolves it against an object or map. In field mode, the final property produces an
+ * extended field without reading its value.
+ *
+ * @param obj object containing the property
+ * @return property value or extended field, or null if it cannot be resolved
+ */
+ private Object readProperty(final Object obj) {
+ String name = readPropertyName();
+ if (null == name || null == obj) {
+ return null;
+ }
+ return findField ? readFieldProperty(obj, name) : readValueProperty(obj, name);
+ }
+
+ /**
+ * Reads the property name at the cursor. Trailing whitespace is ignored when the name ends an alternative.
+ *
+ * @return property name, or null when the name is empty
+ */
+ private String readPropertyName() {
+ int start = index;
+ while (index < length && !isPropertyDelimiter(paths.charAt(index))) {
+ ++index;
+ }
+ int end = index;
+ if (alternatives && (index == length || ',' == paths.charAt(index))) {
+ end = trimEnd(start, end);
+ }
+ if (start == end) {
+ fail();
+ return null;
+ }
+ return paths.substring(start, end);
+ }
+
+ /**
+ * Reads a property value from an object or map.
+ *
+ * @param obj object containing the property
+ * @param name property name
+ * @return property value, or null when it cannot be read
+ */
+ private static Object readValueProperty(final Object obj, final String name) {
+ if (obj instanceof Map, ?> map) {
+ return map.get(name);
+ }
+ return Fields.Safe.get(obj, name);
+ }
+
+ /**
+ * Reads a non-static field and its owner, or the next map value when the path continues.
+ *
+ * @param obj object containing the property
+ * @param name property name
+ * @return extended field, next map value, or null when the property cannot be resolved as a field
+ */
+ private Object readFieldProperty(final Object obj, final String name) {
+ if (obj instanceof Map, ?> map) {
+ return atPathEnd() ? null : map.get(name);
+ }
+ Field field = Fields.Unchecked.getOneDeclaredInHierarchy(obj.getClass(), name);
+ if (null == field || JavaModifier.STATIC.isPresentOn(field)) {
+ return null;
+ }
+ if (atPathEnd()) {
+ return ExtendedField.of(field, obj);
+ }
+ return Fields.IgnoreAccess.get(obj, field);
+ }
+
+ /**
+ * Reads a bracket selector as an array or list index, or as a map key. The opening bracket has already been consumed.
+ *
+ * @param obj container to read
+ * @return selected value, or null if the selector is invalid or cannot be resolved
+ */
+ private Object readBracket(final Object obj) {
+ if (index == length) {
+ return fail();
+ }
+ Object value = isQuote(paths.charAt(index)) ? readQuotedKey(obj) : readUnquotedSelector(obj);
+ if (findField && atPathEnd()) {
+ return null;
+ }
+ return value;
+ }
+
+ /**
+ * Reads a quoted map key and its closing bracket.
+ *
+ * @param obj map containing the key
+ * @return map value, or null if the selector is invalid or the key is absent
+ */
+ private Object readQuotedKey(final Object obj) {
+ char quote = paths.charAt(index);
+ ++index;
+ String key = readQuoted(quote);
+ if (invalid) {
+ return null;
+ }
+ if (!consume(']')) {
+ skipBracket();
+ return fail();
+ }
+ return readMapKey(obj, key);
+ }
+
+ /**
+ * Reads an unquoted array or list index, or a map key, and its closing bracket.
+ *
+ * @param obj container to read
+ * @return selected value, or null if the selector is invalid or cannot be resolved
+ */
+ private Object readUnquotedSelector(final Object obj) {
+ int start = index;
+ boolean numeric = true;
+ while (index < length && ']' != paths.charAt(index)) {
+ char ch = paths.charAt(index);
+ if ('[' == ch || isQuote(ch)) {
+ skipBracket();
+ return fail();
+ }
+ numeric &= Character.isDigit(ch);
+ ++index;
+ }
+ int end = index;
+ if (!consume(']') || start == end) {
+ return fail();
+ }
+ if (!numeric) {
+ return readMapKey(obj, paths.substring(start, end));
+ }
+ try {
+ int elementIndex = Integer.parseInt(paths, start, end, 10);
+ return JavaObjects.getAt(obj, elementIndex);
+ } catch (NumberFormatException e) {
+ return fail();
+ }
+ }
+
+ /**
+ * Reads a string key from a map. Any other container yields null.
+ *
+ * @param obj container
+ * @param key map key
+ * @return map value, or null if {@code obj} is not a map or the key is absent
+ */
+ private static Object readMapKey(final Object obj, final String key) {
+ if (obj instanceof Map, ?> map) {
+ return map.get(key);
+ }
+ return null;
+ }
+
+ /**
+ * Reads a quoted map key, replacing backslash escapes with the escaped characters. The opening quote has already been
+ * consumed.
+ *
+ * @param quote quote character that closes the key
+ * @return unescaped key, or null if the closing quote is missing
+ */
+ private String readQuoted(final char quote) {
+ int start = index;
+ StringBuilder builder = null;
+ while (index < length) {
+ char ch = paths.charAt(index);
+ if (quote == ch) {
+ String key = null == builder
+ ? paths.substring(start, index)
+ : builder.append(paths, start, index).toString();
+ ++index;
+ return key;
+ }
+ if ('\\' == ch) {
+ if (null == builder) {
+ builder = new StringBuilder();
+ }
+ builder.append(paths, start, index);
+ ++index;
+ if (index == length) {
+ invalid = true;
+ return null;
+ }
+ builder.append(paths.charAt(index));
+ start = index + 1;
+ }
+ ++index;
+ }
+ invalid = true;
+ return null;
+ }
+
+ /**
+ * Recovers at a top-level comma, using the same quote and bracket rules as normal parsing.
+ */
+ private void skipInvalidPath() {
+ while (index < length && ',' != paths.charAt(index)) {
+ if (consume('[')) {
+ skipBracket();
+ } else {
+ ++index;
+ }
+ }
+ }
+
+ /**
+ * Consumes the remainder of a bracket, including nested malformed brackets and quoted selectors.
+ */
+ private void skipBracket() {
+ int depth = 1;
+ while (index < length && 0 < depth) {
+ char ch = paths.charAt(index);
+ ++index;
+ if (isQuote(ch)) {
+ readQuoted(ch);
+ } else if ('[' == ch) {
+ ++depth;
+ } else if (']' == ch) {
+ --depth;
+ }
+ }
+ }
+
+ /**
+ * Checks whether the cursor is at the end of the current path, allowing trailing whitespace in alternative mode.
+ *
+ * @return true if the current path ends here
+ */
+ private boolean atPathEnd() {
+ if (index == length) {
+ return true;
+ }
+ int end = index;
+ while (end < length && isWhitespace(paths.charAt(end))) {
+ ++end;
+ }
+ return end == length || ',' == paths.charAt(end);
+ }
+
+ /**
+ * Checks whether a character terminates a property name in the current mode.
+ *
+ * @param ch character to check
+ * @return true if the character terminates a property name
+ */
+ private boolean isPropertyDelimiter(final char ch) {
+ return '.' == ch || '[' == ch || ']' == ch || (alternatives && ',' == ch);
+ }
+
+ /**
+ * Checks whether a character can quote a map key.
+ *
+ * @param ch character to check
+ * @return true for a single or double quote
+ */
+ private static boolean isQuote(final char ch) {
+ return '\'' == ch || '"' == ch;
+ }
+
+ /**
+ * Checks whether a character is whitespace as defined by {@link String#trim()}.
+ *
+ * @param ch character to check
+ * @return true when the character is at most {@code ' '}
+ */
+ private static boolean isWhitespace(final char ch) {
+ return ch <= ' ';
+ }
+
+ /**
+ * Consumes the next character if it matches the expected character.
+ *
+ * @param ch expected character
+ * @return true if the character matched and was consumed
+ */
+ private boolean consume(final char ch) {
+ if (index < length && ch == paths.charAt(index)) {
+ ++index;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Skips whitespace at the cursor.
+ */
+ private void skipWhitespace() {
+ while (index < length && isWhitespace(paths.charAt(index))) {
+ ++index;
+ }
+ }
+
+ /**
+ * Finds the end of a property name after removing trailing whitespace from the given range.
+ *
+ * @param start start of the property name, inclusive
+ * @param end end of the property name, exclusive
+ * @return end index after trailing whitespace is removed
+ */
+ private int trimEnd(final int start, final int end) {
+ int result = end;
+ while (start < result && isWhitespace(paths.charAt(result - 1))) {
+ --result;
+ }
+ return result;
+ }
+
+ /**
+ * Marks the current alternative as invalid.
+ *
+ * @return null so callers can return the failed resolution
+ */
+ private Object fail() {
+ invalid = true;
+ return null;
+ }
+}
diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java
index a0d4af60..c64b3f1e 100644
--- a/src/main/java/org/morphix/reflection/Fields.java
+++ b/src/main/java/org/morphix/reflection/Fields.java
@@ -13,7 +13,6 @@
package org.morphix.reflection;
import java.lang.reflect.Field;
-import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -452,9 +451,11 @@ static void setStatic(final Class cls, final Field field, final U valu
* @param obj object to search the field in
* @param paths possible paths to the field
* @return field value or null if the field is not found or the field value cannot be returned
+ * @throws ReflectionException if {@code paths} is null
*/
static U getByPaths(final T obj, final String... paths) {
- return Safe.getByPaths(obj, paths);
+ Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null");
+ return Unchecked.getByPaths(obj, paths);
}
/**
@@ -469,7 +470,8 @@ static U getByPaths(final T obj, final String... paths) {
* @return field value or null if the field is not found or the field value cannot be returned
*/
static U getByPaths(final T obj, final String paths) {
- return Safe.getByPaths(obj, paths);
+ Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null");
+ return Unchecked.getByPaths(obj, paths);
}
/**
@@ -483,7 +485,8 @@ static U getByPaths(final T obj, final String paths) {
* @return field value or null if the field is not found or the field value cannot be returned
*/
static U getByPath(final T obj, final String path) {
- return Safe.getByPath(obj, path);
+ Reflection.requireNotNull(path, "Cannot resolve field path: path is null");
+ return Unchecked.getByPath(obj, path);
}
}
@@ -799,8 +802,7 @@ static T getStatic(final Field field) {
}
/**
- * Returns the field value for the given object. Field is searched with the field path.
- * TODO: implement full functionality similar to JSON Path
+ * Returns the field value for the given object. Field is searched with the field path.
*
* @param object type
* @param field value type
@@ -808,24 +810,18 @@ static T getStatic(final Field field) {
* @param obj object to search the field in
* @param paths possible paths to the field
* @return field value or null if the field is not found in none of the given paths
- * @throws ReflectionException if {@code paths} is null or a path is null
*/
static U getByPaths(final T obj, final String... paths) {
- Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null");
- U result = null;
- for (String path : paths) {
- result = getByPath(obj, path);
- if (null != result) {
- break;
- }
+ if (null == obj || null == paths) {
+ return null;
}
- return result;
+ return Unchecked.getByPaths(obj, paths);
}
/**
* Variation of {@link Safe#getByPaths(Object, String...)} with paths given as a comma separated list of paths in a
- * single string. Each segment is {@linkplain String#trim() trimmed} after splitting on {@code ','}; empty segments are
- * ignored.
+ * single string. Commas inside brackets are part of the selector. Each path is {@linkplain String#trim() trimmed};
+ * empty alternatives are ignored.
*
* @param object type
* @param field value type
@@ -833,91 +829,35 @@ static U getByPaths(final T obj, final String... paths) {
* @param obj object to search the field in
* @param paths comma separated possible paths to the field
* @return field value or null if the field is not found in none of the given paths
- * @throws ReflectionException if the paths are null
*/
static U getByPaths(final T obj, final String paths) {
- Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null");
- if (paths.isEmpty()) {
- return null;
- }
- String[] parts = paths.split(",", -1);
- List trimmedPaths = new ArrayList<>(parts.length);
- for (String part : parts) {
- String path = part.trim();
- if (!path.isEmpty()) {
- trimmedPaths.add(path);
- }
- }
- if (trimmedPaths.isEmpty()) {
+ if (null == obj || null == paths) {
return null;
}
- return getByPaths(obj, trimmedPaths.toArray(String[]::new));
+ return Unchecked.getByPaths(obj, paths);
}
/**
- * Returns the field value given by its qualified path to the required field in the given object. The field is read
- * directly, without going through a getter method.
+ * Returns the field value given by its path to the required field in the given object. The field is read directly,
+ * without going through a getter method.
+ *
+ * Paths use dot notation for properties (for example {@code inner.value}), bracket notation for array or list indices
+ * (for example {@code items[0].name}), and quoted or unquoted map keys (for example {@code data['key']} or
+ * {@code data[key]}). When a property is not declared on an object, a {@link java.util.Map} value is consulted.
*
* @param object type
* @param field value type
*
* @param obj object to get the field from
- * @param path qualified path to the field
- * @return field value or null if the field is not found or if the object is null
- * @throws ReflectionException if {@code path} is null
+ * @param path path to the value
+ * @return field or container value, or {@code null} if the path is empty, invalid, not found, or {@code obj} is
+ * {@code null}
*/
static U getByPath(final T obj, final String path) {
- Reflection.requireNotNull(path, "Cannot resolve field path: path is null");
- U result = null;
- String[] fieldNames = path.split("\\.", -1);
- if (fieldNames.length == 1) {
- result = Safe.get(obj, fieldNames[0]);
- } else {
- Object value = obj;
- for (String fieldName : fieldNames) {
- value = Safe.get(value, fieldName);
- if (null == value) {
- break;
- }
- }
- if (null != value) {
- result = JavaObjects.cast(value);
- }
- }
- return result;
- }
- }
-
- /**
- * Unsafe utility methods.
- *
- * @author Radu Sebastian LAZIN
- */
- interface Unsafe {
- /**
- * Sets the field value using the {@link TheUnsafe} utility.
- *
- * Primitive fields accept the same widening conversions as {@link Field#set(Object, Object)}. A reference field accepts
- * {@code null} or a value that is an instance of the field type. This is the path used for {@code final} fields, so
- * those fields accept the same values as non-final fields.
- *
- * @param obj object on which the represented field's value is to be set
- * @param field field on which to set the value
- * @param value value to be set on the field
- * @throws IllegalArgumentException if {@code value} is not assignable to the field
- */
- static void set(final Object obj, final Field field, final Object value) {
- boolean isStatic = JavaModifier.STATIC.isPresentOn(field);
- Object instance = isStatic ? TheUnsafe.staticFieldBase(field) : obj;
- long offset = isStatic ? TheUnsafe.staticFieldOffset(field) : TheUnsafe.objectFieldOffset(field);
- Class> type = field.getType();
- if (type.isPrimitive()) {
- TheUnsafe.putPrimitive(instance, offset, type, value);
- } else if (null == value || type.isInstance(value)) {
- TheUnsafe.putObject(instance, offset, value);
- } else {
- throw TheUnsafe.incompatibleValue(type, value);
+ if (null == obj || null == path) {
+ return null;
}
+ return Unchecked.getByPath(obj, path);
}
}
@@ -933,6 +873,8 @@ static void set(final Object obj, final Field field, final Object value) {
* This interface also exposes unchecked field lookup and enumeration helpers used by {@link Safe} and
* {@link IgnoreAccess} so validation is not applied twice. Callers must supply valid arguments and handle
* {@link ReflectionException} and other runtime failures; prefer {@link IgnoreAccess} in application code.
+ *
+ * Path lookup methods return {@code null} for a null root or path; the varargs form requires a non-null array.
*
* @author Radu Sebastian LAZIN
*/
@@ -1184,6 +1126,89 @@ static void set(final Object obj, final Field field, final T value) {
}
});
}
+
+ /**
+ * Returns the first non-null value from the given paths without validating the arguments.
+ *
+ * @param object type
+ * @param field value type
+ *
+ * @param obj object to search
+ * @param paths paths to try in order
+ * @return first non-null value, or null if no path resolves
+ * @throws NullPointerException if the paths array is null
+ */
+ static U getByPaths(final T obj, final String... paths) {
+ for (String path : paths) {
+ U result = getByPath(obj, path);
+ if (null != result) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the first non-null value from comma-separated paths without validating the arguments.
+ *
+ * @param object type
+ * @param field value type
+ *
+ * @param obj object to search
+ * @param paths comma-separated paths
+ * @return first non-null value, or null if the root or paths are null or no path resolves
+ */
+ static U getByPaths(final T obj, final String paths) {
+ return FieldPathParser.resolveFirstValue(obj, paths);
+ }
+
+ /**
+ * Returns the value at a single path without validating the arguments.
+ *
+ * @param object type
+ * @param field value type
+ *
+ * @param obj object to search
+ * @param path path to resolve
+ * @return value, or null if the root or path is null or the path cannot be resolved
+ */
+ static U getByPath(final T obj, final String path) {
+ return FieldPathParser.resolveValue(obj, path);
+ }
+ }
+
+ /**
+ * Unsafe utility methods.
+ *
+ * @author Radu Sebastian LAZIN
+ */
+ interface Unsafe {
+
+ /**
+ * Sets the field value using the {@link TheUnsafe} utility.
+ *
+ * Primitive fields accept the same widening conversions as {@link Field#set(Object, Object)}. A reference field accepts
+ * {@code null} or a value that is an instance of the field type. This is the path used for {@code final} fields, so
+ * those fields accept the same values as non-final fields.
+ *
+ * @param obj object on which the represented field's value is to be set
+ * @param field field on which to set the value
+ * @param value value to be set on the field
+ * @throws IllegalArgumentException if {@code value} is not assignable to the field
+ */
+ static void set(final Object obj, final Field field, final Object value) {
+ boolean isStatic = JavaModifier.STATIC.isPresentOn(field);
+ Object instance = isStatic ? TheUnsafe.staticFieldBase(field) : obj;
+ long offset = isStatic ? TheUnsafe.staticFieldOffset(field) : TheUnsafe.objectFieldOffset(field);
+ Class> type = field.getType();
+ if (type.isPrimitive()) {
+ TheUnsafe.putPrimitive(instance, offset, type, value);
+ } else if (null == value || type.isInstance(value)) {
+ TheUnsafe.putObject(instance, offset, value);
+ } else {
+ throw TheUnsafe.incompatibleValue(type, value);
+ }
+ }
}
/**
diff --git a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java
index b0a40d0b..a38062e0 100644
--- a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java
+++ b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java
@@ -17,6 +17,9 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.morphix.convert.Conversions.convertFrom;
+import java.util.List;
+import java.util.Map;
+
import org.junit.jupiter.api.Test;
/**
@@ -142,4 +145,36 @@ void shouldDeepConvertStaticStringEvenIfPathMatches() {
assertThat(dst.l, nullValue());
assertThat(dst.x, equalTo(TEST_LONG));
}
+
+ public static class IndexedSource {
+
+ List items;
+
+ Map keyed;
+ }
+
+ public static class IndexedDestination {
+
+ @Src("items[0].s")
+ Long indexed;
+
+ @Src("items[9].s,keyed['a,b'].s")
+ Long alternative;
+ }
+
+ @Test
+ void shouldDeepConvertIndexedAndAlternativePaths() {
+ A first = new A();
+ first.s = "10";
+ A second = new A();
+ second.s = "20";
+ IndexedSource src = new IndexedSource();
+ src.items = List.of(first);
+ src.keyed = Map.of("a,b", second);
+
+ IndexedDestination dst = convertFrom(src, IndexedDestination::new);
+
+ assertThat(dst.indexed, equalTo(10L));
+ assertThat(dst.alternative, equalTo(20L));
+ }
}
diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java
new file mode 100644
index 00000000..4a2d8baf
--- /dev/null
+++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2026 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+package org.morphix.convert.strategy;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import java.util.HashMap;
+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.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.morphix.reflection.ExtendedField;
+import org.morphix.reflection.Fields;
+
+/**
+ * Test class for {@link FinderPathStrategy}.
+ *
+ * @author Radu Sebastian LAZIN
+ */
+class FinderPathStrategyTest {
+
+ public static class Entry {
+
+ public static String staticName = "static";
+
+ @SuppressWarnings("unused")
+ private String name;
+
+ private Entry(final String name) {
+ this.name = name;
+ }
+ }
+
+ public static class Source {
+
+ private final Entry[] entries = { new Entry("array"), new Entry(null) };
+
+ private final List items = List.of(new Entry("list"));
+
+ private final Map keyed = Map.of("a,b", new Entry("map"), "key", new Entry("plain"));
+
+ @SuppressWarnings("unused")
+ private final Entry missing = null;
+ }
+
+ @Test
+ void shouldFindFinalFieldAndItsOwnerThroughContainers() {
+ Source source = new Source();
+ FinderPathStrategy strategy = new FinderPathStrategy();
+
+ assertField(strategy.find(source, List.of(), "entries[0].name"), source.entries[0], "array");
+ assertField(strategy.find(source, List.of(), "items[0].name"), source.items.get(0), "list");
+ assertField(strategy.find(source, List.of(), "keyed['a,b'].name"), source.keyed.get("a,b"), "map");
+ assertField(strategy.find(source, List.of(), "keyed[key].name"), source.keyed.get("key"), "plain");
+ assertField(strategy.find(source, List.of(), "keyed.key.name"), source.keyed.get("key"), "plain");
+ assertField(strategy.find(source.entries, List.of(), "[0].name"), source.entries[0], "array");
+ }
+
+ @Test
+ void shouldFindFirstExistingFieldAmongAlternatives() {
+ Source source = new Source();
+ ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source,
+ " , missing.name, entries[9].name, keyed['a,b'].name, items[0].name ");
+
+ assertField(field, source.keyed.get("a,b"), "map");
+ }
+
+ @Test
+ void shouldFindFirstMatchingFieldAmongSkippingInvalidAlternatives() {
+ Source source = new Source();
+
+ ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source,
+ " , missing.name, items[9].name, entries[0].name ");
+
+ assertField(field, source.entries[0], "array");
+ }
+
+ @Test
+ void shouldFindNullValuedFieldWithoutTryingFollowingAlternative() {
+ Source source = new Source();
+ String paths = "entries[1].name,items[0].name";
+
+ ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, paths);
+
+ assertField(field, source.entries[1], null);
+ assertThat(Fields.Safe.getByPaths(source, paths), equalTo("list"));
+
+ FinderPathStrategy strategy = new FinderPathStrategy();
+ assertField(strategy.find(source, List.of(), "entries[1].name , items[0].name"), source.entries[1], null);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fieldPathsWithTrailingPadding")
+ void shouldFindFieldWhenAlternativeAllowsTrailingPadding(final String paths) {
+ Source source = new Source();
+ FinderPathStrategy strategy = new FinderPathStrategy();
+
+ assertField(strategy.find(source, List.of(), paths), source.entries[0], "array");
+ }
+
+ private static Stream fieldPathsWithTrailingPadding() {
+ return Stream.of(
+ "entries[0].name ",
+ "entries[0].name ",
+ "entries[0].name\t",
+ "entries[0].name , items[0].name",
+ " entries[0].name ");
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "",
+ ", ,",
+ "missing.name,items[9].name",
+ "items[0]",
+ "keyed['key']",
+ "keyed['key'] ",
+ "entries[0].staticName"
+ })
+ void shouldReturnEmptyWhenNoAlternativeMatches(final String paths) {
+ Source source = new Source();
+
+ ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, paths);
+
+ assertThat(field, sameInstance(ExtendedField.EMPTY));
+ }
+
+ @Test
+ void shouldReturnEmptyForNullPaths() {
+ Source source = new Source();
+
+ ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, null);
+
+ assertThat(field, sameInstance(ExtendedField.EMPTY));
+ }
+
+ @Test
+ void shouldRejectStaticFieldsAndContainerElementsAsTerminalFields() {
+ Source source = new Source();
+
+ for (String path : List.of("entries[0].staticName", "entries[0]", "keyed['a,b']", "keyed['a,b'] ",
+ "keyed.key", "missing.name", "entries[0].", "entries[0].name[0]")) {
+ assertThat(path, FinderPathStrategy.getConverterFieldByPathInHierarchy(source, path),
+ sameInstance(ExtendedField.EMPTY));
+ }
+ assertThat(FinderPathStrategy.getConverterFieldByPathInHierarchy(null, "entries[0].name"),
+ sameInstance(ExtendedField.EMPTY));
+ assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0].staticName,items[0].name"),
+ source.items.get(0), "list");
+ assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0],items[0].name"),
+ source.items.get(0), "list");
+ }
+
+ @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"));
+ assertThat(field.getField().getDeclaringClass(), equalTo(Entry.class));
+ if (null == value) {
+ assertThat(field.getFieldValue(), nullValue());
+ } else {
+ assertThat(field.getFieldValue(), equalTo(value));
+ }
+ }
+}
diff --git a/src/test/java/org/morphix/lang/JavaArraysTest.java b/src/test/java/org/morphix/lang/JavaArraysTest.java
index 5400b418..25ba11de 100644
--- a/src/test/java/org/morphix/lang/JavaArraysTest.java
+++ b/src/test/java/org/morphix/lang/JavaArraysTest.java
@@ -14,6 +14,7 @@
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -22,6 +23,7 @@
import java.util.Arrays;
import java.util.List;
+import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
@@ -31,203 +33,316 @@
*/
class JavaArraysTest {
- @Test
- void shouldReturnEmptyArrayWhenNullProvided() {
- String[] result = JavaArrays.safe(null, String.class);
+ @Nested
+ class SafeTests {
- assertNotNull(result);
- assertThat(result.length, equalTo(0));
- }
+ @Test
+ void shouldReturnEmptyArrayWhenNullProvided() {
+ String[] result = JavaArrays.safe(null, String.class);
+
+ assertNotNull(result);
+ assertThat(result.length, equalTo(0));
+ }
- @Test
- void shouldReturnSameArrayWhenNotNullProvided() {
- String[] input = new String[] { "a", "b", "c" };
- String[] result = JavaArrays.safe(input, String.class);
+ @Test
+ void shouldReturnSameArrayWhenNotNullProvided() {
+ String[] input = new String[] { "a", "b", "c" };
+ String[] result = JavaArrays.safe(input, String.class);
- assertThat(result, equalTo(input));
+ assertThat(result, equalTo(input));
+ }
}
- @Test
- void shouldReturnNullWhenEmptyArrayProvided() {
- Integer[] input = new Integer[] { };
- Integer[] result = JavaArrays.nullIfEmpty(input);
+ @Nested
+ class NullIfEmptyTests {
- assertThat(result, equalTo(null));
- }
+ @Test
+ void shouldReturnNullWhenEmptyArrayProvided() {
+ Integer[] input = new Integer[] { };
+ Integer[] result = JavaArrays.nullIfEmpty(input);
+
+ assertThat(result, equalTo(null));
+ }
- @Test
- void shouldReturnSameArrayWhenNonEmptyArrayProvided() {
- Integer[] input = new Integer[] { 1, 2, 3 };
- Integer[] result = JavaArrays.nullIfEmpty(input);
+ @Test
+ void shouldReturnSameArrayWhenNonEmptyArrayProvided() {
+ Integer[] input = new Integer[] { 1, 2, 3 };
+ Integer[] result = JavaArrays.nullIfEmpty(input);
- assertThat(result, equalTo(input));
+ assertThat(result, equalTo(input));
+ }
}
- @Test
- void shouldConvertNullInputToEmptyArray() {
- Object[] result = JavaArrays.toArray(null);
+ @Nested
+ class ToArrayTests {
- assertThat(result, sameInstance(JavaArrays.EMPTY));
- }
+ @Test
+ void shouldConvertNullInputToEmptyArray() {
+ Object[] result = JavaArrays.toArray(null);
- @Test
- void shouldConvertPrimitiveArrayToObjectArray() {
- int[] intArray = new int[] { 1, 2, 3 };
+ assertThat(result, sameInstance(JavaArrays.EMPTY));
+ }
- Object[] result = JavaArrays.toArray(intArray);
+ @Test
+ void shouldConvertSingleObjectInputToObjectArray() {
+ Integer singleValue = 42;
- assertThat(result, equalTo(new Object[] { 1, 2, 3 }));
- }
+ Object[] result = JavaArrays.toArray(singleValue);
- @Test
- void shouldConvertIterableToObjectArray() {
- List list = Arrays.asList("x", "y", "z");
+ assertThat(result, equalTo(new Object[] { 42 }));
+ }
- Object[] result = JavaArrays.toArray(list);
+ @Nested
+ class PrimitiveArrayTests {
- assertThat(result, equalTo(new Object[] { "x", "y", "z" }));
- }
+ @Test
+ void shouldConvertPrimitiveArrayToObjectArray() {
+ int[] intArray = new int[] { 1, 2, 3 };
- @Test
- void shouldConvertSingleObjectInputToObjectArray() {
- Integer singleValue = 42;
+ Object[] result = JavaArrays.toArray(intArray);
- Object[] result = JavaArrays.toArray(singleValue);
+ assertThat(result, equalTo(new Object[] { 1, 2, 3 }));
+ }
- assertThat(result, equalTo(new Object[] { 42 }));
- }
+ @Test
+ void shouldReturnSharedEmptyForEmptyPrimitiveArray() {
+ Object[] result = JavaArrays.toArray(new int[0]);
- @Test
- void shouldConvertObjectArrayInputToObjectArray() {
- Object[] inputArray = new Object[] { "a", 1, true };
+ assertThat(result, sameInstance(JavaArrays.EMPTY));
+ }
+ }
- Object[] result = JavaArrays.toArray(inputArray);
+ @Nested
+ class IterableTests {
- assertThat(result, equalTo(new Object[] { "a", 1, true }));
- assertThat(result, not(sameInstance(inputArray)));
- }
+ @Test
+ void shouldConvertIterableToObjectArray() {
+ List list = Arrays.asList("x", "y", "z");
- @Test
- void shouldReturnSharedEmptyForEmptyObjectArrayInput() {
- assertThat(JavaArrays.toArray(new Object[0]), sameInstance(JavaArrays.EMPTY));
- }
+ Object[] result = JavaArrays.toArray(list);
- @Test
- void shouldReturnSharedEmptyForEmptyPrimitiveArrayInput() {
- assertThat(JavaArrays.toArray(new int[0]), sameInstance(JavaArrays.EMPTY));
- }
+ assertThat(result, equalTo(new Object[] { "x", "y", "z" }));
+ }
- @Test
- void shouldReturnSharedEmptyForEmptyIterableInput() {
- assertThat(JavaArrays.toArray(List.of()), sameInstance(JavaArrays.EMPTY));
- }
+ @Test
+ void shouldReturnSharedEmptyForEmptyIterable() {
+ Object[] result = JavaArrays.toArray(List.of());
- @Test
- void shouldCloneEmptyReferenceArrayWithComponentTypeOtherThanObject() {
- String[] input = new String[0];
+ assertThat(result, sameInstance(JavaArrays.EMPTY));
+ }
+ }
- Object[] result = JavaArrays.toArray(input);
+ @Nested
+ class ObjectArrayTests {
- assertThat(result.length, equalTo(0));
- assertThat(result.getClass().getComponentType(), equalTo(String.class));
- assertThat(result, not(sameInstance(input)));
- assertThat(result, not(sameInstance(JavaArrays.EMPTY)));
- }
+ @Test
+ void shouldConvertObjectArrayInputToObjectArray() {
+ Object[] inputArray = new Object[] { "a", 1, true };
- @Test
- void shouldConvertStringArrayInputToObjectArray() {
- String[] stringArray = new String[] { "a", "b", "c" };
+ Object[] result = JavaArrays.toArray(inputArray);
- Object[] result = JavaArrays.toArray(stringArray);
+ assertThat(result, equalTo(new Object[] { "a", 1, true }));
+ assertThat(result, not(sameInstance(inputArray)));
+ }
- assertThat(result, equalTo(new Object[] { "a", "b", "c" }));
- }
+ @Test
+ void shouldReturnSharedEmptyForEmptyObjectArray() {
+ Object[] result = JavaArrays.toArray(new Object[0]);
- @Test
- void shouldReturnFalseForNonEmptyArrayOnIsEmpty() {
- String[] array = new String[] { "not", "empty" };
+ assertThat(result, sameInstance(JavaArrays.EMPTY));
+ }
+ }
- boolean result = JavaArrays.isEmpty(array);
+ @Nested
+ class ReferenceArrayTests {
- assertThat(result, equalTo(false));
- }
+ @Test
+ void shouldConvertStringArrayInputToObjectArray() {
+ String[] stringArray = new String[] { "a", "b", "c" };
+
+ Object[] result = JavaArrays.toArray(stringArray);
- @Test
- void shouldReturnTrueForEmptyArrayOnIsEmpty() {
- String[] array = new String[] { };
+ assertThat(result, equalTo(new Object[] { "a", "b", "c" }));
+ }
- boolean result = JavaArrays.isEmpty(array);
+ @Test
+ void shouldCloneEmptyReferenceArrayWithComponentTypeOtherThanObject() {
+ String[] input = new String[0];
- assertThat(result, equalTo(true));
+ Object[] result = JavaArrays.toArray(input);
+
+ assertThat(result.length, equalTo(0));
+ assertThat(result.getClass().getComponentType(), equalTo(String.class));
+ assertThat(result, not(sameInstance(input)));
+ assertThat(result, not(sameInstance(JavaArrays.EMPTY)));
+ }
+ }
}
- @Test
- void shouldReturnTrueForNullArrayOnIsEmpty() {
- String[] array = null;
+ @Nested
+ class IsEmptyTests {
- boolean result = JavaArrays.isEmpty(array);
+ @Test
+ void shouldReturnFalseForNonEmptyArray() {
+ String[] array = new String[] { "not", "empty" };
- assertThat(result, equalTo(true));
- }
+ boolean result = JavaArrays.isEmpty(array);
- @Test
- void shouldReturnTrueForNonEmptyArrayOnIsNotEmpty() {
- String[] array = new String[] { "not", "empty" };
+ assertThat(result, equalTo(false));
+ }
- boolean result = JavaArrays.isNotEmpty(array);
+ @Test
+ void shouldReturnTrueForEmptyArray() {
+ String[] array = new String[] { };
- assertThat(result, equalTo(true));
- }
+ boolean result = JavaArrays.isEmpty(array);
+
+ assertThat(result, equalTo(true));
+ }
- @Test
- void shouldReturnFalseForEmptyArrayOnIsNotEmpty() {
- String[] array = new String[] { };
+ @Test
+ void shouldReturnTrueForNullArray() {
+ String[] array = null;
- boolean result = JavaArrays.isNotEmpty(array);
+ boolean result = JavaArrays.isEmpty(array);
- assertThat(result, equalTo(false));
+ assertThat(result, equalTo(true));
+ }
}
- @Test
- void shouldReturnEmptyArrayForGivenComponentType() {
- String[] result = JavaArrays.empty(String.class);
+ @Nested
+ class IsNotEmptyTests {
- assertNotNull(result);
- assertThat(result.length, equalTo(0));
- assertThat(result.getClass().getComponentType(), equalTo(String.class));
- }
+ @Test
+ void shouldReturnTrueForNonEmptyArray() {
+ String[] array = new String[] { "not", "empty" };
- @Test
- void shouldReturnSharedEmptyForObjectComponentType() {
- assertThat(JavaArrays.empty(Object.class), sameInstance(JavaArrays.EMPTY));
- }
+ boolean result = JavaArrays.isNotEmpty(array);
- @Test
- void shouldReturnEmptyArrayForCustomComponentType() {
- JavaArraysTest[] result = JavaArrays.empty(JavaArraysTest.class);
+ assertThat(result, equalTo(true));
+ }
- assertNotNull(result);
- assertThat(result.length, equalTo(0));
- assertThat(result.getClass().getComponentType(), equalTo(JavaArraysTest.class));
- }
+ @Test
+ void shouldReturnFalseForEmptyArray() {
+ String[] array = new String[] { };
- @Test
- void shouldReturnNewEmptyArrayOnEachCall() {
- String[] first = JavaArrays.empty(String.class);
- String[] second = JavaArrays.empty(String.class);
+ boolean result = JavaArrays.isNotEmpty(array);
- assertThat(first, not(sameInstance(second)));
+ assertThat(result, equalTo(false));
+ }
}
- @Test
- void shouldThrowWhenComponentTypeIsNull() {
- assertThrows(NullPointerException.class, () -> JavaArrays.empty(null));
+ @Nested
+ class EmptyTests {
+
+ @Test
+ void shouldReturnEmptyArrayForGivenComponentType() {
+ String[] result = JavaArrays.empty(String.class);
+
+ assertNotNull(result);
+ assertThat(result.length, equalTo(0));
+ assertThat(result.getClass().getComponentType(), equalTo(String.class));
+ }
+
+ @Test
+ void shouldReturnSharedEmptyForObjectComponentType() {
+ Object[] result = JavaArrays.empty(Object.class);
+
+ assertThat(result, sameInstance(JavaArrays.EMPTY));
+ }
+
+ @Test
+ void shouldReturnEmptyArrayForCustomComponentType() {
+ JavaArraysTest[] result = JavaArrays.empty(JavaArraysTest.class);
+
+ assertNotNull(result);
+ assertThat(result.length, equalTo(0));
+ assertThat(result.getClass().getComponentType(), equalTo(JavaArraysTest.class));
+ }
+
+ @Test
+ void shouldReturnNewEmptyArrayOnEachCall() {
+ String[] first = JavaArrays.empty(String.class);
+ String[] second = JavaArrays.empty(String.class);
+
+ assertThat(first, not(sameInstance(second)));
+ }
+
+ @Test
+ void shouldThrowWhenComponentTypeIsNull() {
+ assertThrows(NullPointerException.class, () -> JavaArrays.empty(null));
+ }
+
+ @Test
+ void shouldThrowWhenComponentTypeIsPrimitive() {
+ IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> JavaArrays.empty(int.class));
+
+ assertThat(e.getMessage(), equalTo("Component type cannot be a primitive: int"));
+ }
}
- @Test
- void shouldThrowWhenComponentTypeIsPrimitive() {
- IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> JavaArrays.empty(int.class));
+ @Nested
+ class SafeGetTests {
+
+ @Test
+ void shouldReturnNullForNullArray() {
+ String result = JavaArrays.safeGet(null, 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForNegativeIndex() {
+ String[] array = { "a", "b" };
+
+ String result = JavaArrays.safeGet(array, -1);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullWhenIndexEqualsLength() {
+ String[] array = { "a", "b" };
+
+ String result = JavaArrays.safeGet(array, array.length);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForEmptyArray() {
+ String[] array = { };
+
+ String result = JavaArrays.safeGet(array, 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnElementAtFirstIndex() {
+ String[] array = { "a", "b", "c" };
+
+ String result = JavaArrays.safeGet(array, 0);
+
+ assertThat(result, equalTo("a"));
+ }
+
+ @Test
+ void shouldReturnElementAtLastIndex() {
+ String[] array = { "a", "b", "c" };
+
+ String result = JavaArrays.safeGet(array, array.length - 1);
+
+ assertThat(result, equalTo("c"));
+ }
+
+ @Test
+ void shouldReturnNullElementStoredInArray() {
+ String[] array = { null };
+
+ String result = JavaArrays.safeGet(array, 0);
- assertThat(e.getMessage(), equalTo("Component type cannot be a primitive: int"));
+ assertThat(result, nullValue());
+ }
}
}
diff --git a/src/test/java/org/morphix/lang/JavaObjectsTest.java b/src/test/java/org/morphix/lang/JavaObjectsTest.java
index 81d659d5..529890ae 100644
--- a/src/test/java/org/morphix/lang/JavaObjectsTest.java
+++ b/src/test/java/org/morphix/lang/JavaObjectsTest.java
@@ -15,6 +15,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -22,6 +23,7 @@
import static org.mockito.Mockito.mock;
import java.util.Collection;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -40,6 +42,17 @@ class JavaObjectsTest {
private static final String BUBU = "Bubu";
private static final String CUCU = "Cucu";
+ @Nested
+ class ConstructorTests {
+
+ @Test
+ void shouldThrowExceptionWhenTryingToInstantiate() {
+ UnsupportedOperationException e = Tests.verifyDefaultConstructorThrows(JavaObjects.class);
+
+ assertThat(e.getMessage(), equalTo(Constructors.MESSAGE_THIS_CLASS_SHOULD_NOT_BE_INSTANTIATED));
+ }
+ }
+
@Nested
class CastTests {
@@ -53,13 +66,6 @@ void shouldCastToInferredType() {
assertThat(bubu, equalTo(BUBU));
}
- @Test
- void shouldThrowExceptionWhenTryingToInstantiate() {
- UnsupportedOperationException e = Tests.verifyDefaultConstructorThrows(JavaObjects.class);
-
- assertThat(e.getMessage(), equalTo(Constructors.MESSAGE_THIS_CLASS_SHOULD_NOT_BE_INSTANTIATED));
- }
-
@Test
void shouldThrowClassCastExceptionWhenObjectCannotBeCastToInferredType() {
String x = CUCU;
@@ -336,4 +342,143 @@ void shouldReturnTrueWhenOneObjectIsNull() {
assertFalse(JavaObjects.notEquals(null, null));
}
}
+
+ @Nested
+ class GetAtTests {
+
+ @Test
+ void shouldReturnNullForNullObject() {
+ Object result = JavaObjects.getAt(null, 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForNegativeIndex() {
+ Object result = JavaObjects.getAt(new String[] { "a" }, -1);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForNonContainer() {
+ Object result = JavaObjects.getAt("ab", 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Nested
+ class ListTests {
+
+ @Test
+ void shouldReturnElementAtFirstIndex() {
+ List list = List.of("a", "b", "c");
+
+ String result = JavaObjects.getAt(list, 0);
+
+ assertThat(result, equalTo("a"));
+ }
+
+ @Test
+ void shouldReturnElementAtLastIndex() {
+ List list = List.of("a", "b", "c");
+
+ String result = JavaObjects.getAt(list, list.size() - 1);
+
+ assertThat(result, equalTo("c"));
+ }
+
+ @Test
+ void shouldReturnNullWhenIndexEqualsSize() {
+ List list = List.of("a", "b");
+
+ Object result = JavaObjects.getAt(list, list.size());
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForEmptyList() {
+ Object result = JavaObjects.getAt(List.of(), 0);
+
+ assertThat(result, nullValue());
+ }
+ }
+
+ @Nested
+ class ObjectArrayTests {
+
+ @Test
+ void shouldReturnElementAtFirstIndex() {
+ String[] array = { "a", "b", "c" };
+
+ String result = JavaObjects.getAt(array, 0);
+
+ assertThat(result, equalTo("a"));
+ }
+
+ @Test
+ void shouldReturnElementAtLastIndex() {
+ String[] array = { "a", "b", "c" };
+
+ String result = JavaObjects.getAt(array, array.length - 1);
+
+ assertThat(result, equalTo("c"));
+ }
+
+ @Test
+ void shouldReturnNullWhenIndexEqualsLength() {
+ String[] array = { "a", "b" };
+
+ Object result = JavaObjects.getAt(array, array.length);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForEmptyArray() {
+ Object result = JavaObjects.getAt(new String[0], 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullElementStoredInArray() {
+ String[] array = { null };
+
+ Object result = JavaObjects.getAt(array, 0);
+
+ assertThat(result, nullValue());
+ }
+ }
+
+ @Nested
+ class PrimitiveArrayTests {
+
+ @Test
+ void shouldReturnElementAtFirstIndex() {
+ int[] array = { 10, 20, 30 };
+
+ Integer result = JavaObjects.getAt(array, 0);
+
+ assertThat(result, equalTo(10));
+ }
+
+ @Test
+ void shouldReturnElementAtLastIndex() {
+ int[] array = { 10, 20, 30 };
+
+ Integer result = JavaObjects.getAt(array, array.length - 1);
+
+ assertThat(result, equalTo(30));
+ }
+
+ @Test
+ void shouldReturnNullForEmptyArray() {
+ Object result = JavaObjects.getAt(new int[0], 0);
+
+ assertThat(result, nullValue());
+ }
+ }
+ }
}
diff --git a/src/test/java/org/morphix/lang/collections/ListsTest.java b/src/test/java/org/morphix/lang/collections/ListsTest.java
index da241155..fe4c5101 100644
--- a/src/test/java/org/morphix/lang/collections/ListsTest.java
+++ b/src/test/java/org/morphix/lang/collections/ListsTest.java
@@ -21,6 +21,7 @@
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.sameInstance;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
@@ -342,4 +343,58 @@ void shouldNoPartitionsForNonPositiveSize() {
assertThat(result, empty());
}
}
+
+ @Nested
+ class SafeGetTests {
+
+ @Test
+ void shouldReturnNullForNullList() {
+ String result = Lists.safeGet(null, 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForEmptyList() {
+ String result = Lists.safeGet(List.of(), 0);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullForNegativeIndex() {
+ List list = List.of("a", "b");
+
+ String result = Lists.safeGet(list, -1);
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullWhenIndexEqualsSize() {
+ List list = List.of("a", "b");
+
+ String result = Lists.safeGet(list, list.size());
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnElementAtFirstAndLastIndex() {
+ List list = List.of("a", "b", "c");
+
+ assertThat(Lists.safeGet(list, 0), equalTo("a"));
+ assertThat(Lists.safeGet(list, list.size() - 1), equalTo("c"));
+ }
+
+ @Test
+ void shouldReturnNullElementStoredInList() {
+ List list = new ArrayList<>();
+ list.add(null);
+
+ String result = Lists.safeGet(list, 0);
+
+ assertThat(result, nullValue());
+ }
+ }
}
diff --git a/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java
index 012f9170..84c92ffd 100644
--- a/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java
+++ b/src/test/java/org/morphix/reflection/FieldsIgnoreAccessGetByPathsTest.java
@@ -15,6 +15,7 @@
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@@ -115,4 +116,58 @@ void shouldReturnNullForEmptySearch() {
assertThat(result, nullValue());
}
+
+ @Test
+ void shouldThrowWhenPathsArrayIsNull() {
+ B b = new B();
+
+ ReflectionException exception = assertThrows(ReflectionException.class,
+ () -> Fields.IgnoreAccess.getByPaths(b, (String[]) null));
+
+ assertThat(exception.getMessage(), equalTo("Cannot resolve field paths: paths are null"));
+ }
+
+ @Test
+ void shouldThrowWhenCommaSeparatedPathsAreNull() {
+ B b = new B();
+
+ ReflectionException exception = assertThrows(ReflectionException.class,
+ () -> Fields.IgnoreAccess.getByPaths(b, (String) null));
+
+ assertThat(exception.getMessage(), equalTo("Cannot resolve field paths: paths are null"));
+ }
+
+ @Test
+ void shouldThrowWhenSinglePathIsNull() {
+ B b = new B();
+
+ ReflectionException exception = assertThrows(ReflectionException.class,
+ () -> Fields.IgnoreAccess.getByPath(b, null));
+
+ assertThat(exception.getMessage(), equalTo("Cannot resolve field path: path is null"));
+ }
+
+ @Test
+ void shouldSkipNullVarargsPath() {
+ A a = new A();
+ a.x = TEST_STRING;
+ B b = new B();
+ b.a = a;
+
+ var result = Fields.IgnoreAccess.getByPaths(b, null, "a.x");
+
+ assertThat(result, equalTo(TEST_STRING));
+ }
+
+ @Test
+ void shouldResolveFirstNonNullVarargsPath() {
+ A a = new A();
+ a.x = TEST_STRING;
+ B b = new B();
+ b.a = a;
+
+ var result = Fields.IgnoreAccess.getByPaths(b, "missing", "a.x");
+
+ assertThat(result, equalTo(TEST_STRING));
+ }
}
diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java
index 44fa7824..130aaa85 100644
--- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java
+++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java
@@ -15,9 +15,17 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+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;
/**
* Test class for {@link Fields.Safe#getByPath(Object, String)}.
@@ -30,7 +38,7 @@ class FieldsSafeGetByPathTest {
private static final String GETTER_VALUE = "getterValue";
- private static final String NON_EXISTENT_FIELD = "$NonExistentField$";
+ private final Data data = new Data();
public static class WithTransformingGetter {
@@ -55,76 +63,150 @@ void shouldGetFieldAtFirstLevel() {
assertThat(result, equalTo(obj.inner));
}
- @Test
- void shouldGetNestedField() {
- WithNestedField obj = new WithNestedField();
-
- Object result = Fields.Safe.getByPath(obj, "inner.value");
+ @ParameterizedTest
+ @MethodSource("getterPaths")
+ void shouldReadTheFieldAndNotTheGetter(final Object root, final String path) {
+ var result = Fields.Safe.getByPath(root, path);
assertThat(result, equalTo(FIELD_VALUE));
}
- @Test
- void shouldReturnNullIfFieldDoesNotExistAtFirstLevel() {
- WithNestedField obj = new WithNestedField();
+ private static Stream getterPaths() {
+ return Stream.of(
+ Arguments.of(new WithTransformingGetter(), "value"),
+ Arguments.of(new WithNestedField(), "inner.value"));
+ }
- Object result = Fields.Safe.getByPath(obj, NON_EXISTENT_FIELD);
+ @Test
+ void shouldReturnNullIfObjectIsNull() {
+ Object result = Fields.Safe.getByPath(null, "value");
assertThat(result, nullValue());
}
@Test
- void shouldReturnNullIfNestedFieldDoesNotExist() {
- WithNestedField obj = new WithNestedField();
-
- Object result = Fields.Safe.getByPath(obj, "inner." + NON_EXISTENT_FIELD);
+ void shouldReturnNullWhenPathIsNull() {
+ var result = Fields.Safe.getByPath(new WithNestedField(), null);
assertThat(result, nullValue());
}
- @Test
- void shouldReturnNullIfIntermediateFieldIsNull() {
- WithNestedField obj = new WithNestedField();
- obj.inner = null;
+ private record Person(String name) {
+ // empty
+ }
- Object result = Fields.Safe.getByPath(obj, "inner.value");
+ @SuppressWarnings("unused")
+ private static final class Data {
- assertThat(result, nullValue());
- }
+ private final Person person = new Person("Alice");
- @Test
- void shouldReturnNullForEmptyPath() {
- Object result = Fields.Safe.getByPath(new WithNestedField(), "");
+ private final List persons = List.of(
+ new Person("Alice"),
+ new Person("Bob"));
- assertThat(result, nullValue());
- }
+ private final String[] array = { "Alice", "Bob" };
- @Test
- void shouldReturnNullForPathWithTrailingDot() {
- Object result = Fields.Safe.getByPath(new WithNestedField(), "inner.");
+ private final int[] numbers = { 10, 20, 30 };
- assertThat(result, nullValue());
+ private final int[][] matrix = {
+ { 10, 20 },
+ { 30, 40 }
+ };
+
+ private final Map attributes = Map.of(
+ "name", "Alice",
+ "first.name", "Bob",
+ "a,b", "comma",
+ "a]b", "bracket",
+ "a'b", "quote",
+ "a\\b", "backslash",
+ "0", "zero",
+ "", "empty",
+ "size", "map size");
+
+ private final Object missing = null;
}
- @Test
- void shouldReadTheFieldAndNotTheGetterOnASingleSegmentPath() {
- WithTransformingGetter obj = new WithTransformingGetter();
+ @ParameterizedTest
+ @MethodSource("resolvedPaths")
+ void shouldResolvePath(final String path, final Object expected) {
+ var result = Fields.Safe.getByPath(data, path);
- Object result = Fields.Safe.getByPath(obj, "value");
+ assertThat(result, equalTo(expected));
+ }
- assertThat(result, equalTo(FIELD_VALUE));
+ private static Stream resolvedPaths() {
+ return Stream.of(
+ Arguments.of("person.name", "Alice"),
+ Arguments.of("persons[0]", new Person("Alice")),
+ Arguments.of("persons[0].name", "Alice"),
+ Arguments.of("persons[1].name", "Bob"),
+ Arguments.of("array[0]", "Alice"),
+ Arguments.of("array[1]", "Bob"),
+ Arguments.of("numbers[1]", 20),
+ Arguments.of("matrix[1][0]", 30),
+ Arguments.of("attributes.name", "Alice"),
+ Arguments.of("attributes[name]", "Alice"),
+ Arguments.of("attributes['name']", "Alice"),
+ Arguments.of("attributes[\"name\"]", "Alice"),
+ Arguments.of("attributes['first.name']", "Bob"),
+ Arguments.of("attributes['0']", "zero"),
+ Arguments.of("attributes['']", "empty"),
+ Arguments.of("attributes.size", "map size"),
+ Arguments.of("attributes['a]b']", "bracket"),
+ Arguments.of("attributes['a,b']", "comma"),
+ Arguments.of("attributes['a\\'b']", "quote"),
+ Arguments.of("attributes['a\\\\b']", "backslash"));
}
- @Test
- void shouldReturnNullIfObjectIsNull() {
- Object result = Fields.Safe.getByPath(null, "value");
+ @ParameterizedTest
+ @MethodSource("rootPaths")
+ void shouldResolveRootContainer(final Object root, final String path, final Object expected) {
+ var result = Fields.Safe.getByPath(root, path);
- assertThat(result, nullValue());
+ assertThat(result, equalTo(expected));
}
- @Test
- void shouldThrowWhenPathIsNull() {
- ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPath(new WithNestedField(), null));
- assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null"));
+ private static Stream rootPaths() {
+ return Stream.of(
+ Arguments.of(List.of(new Person("Alice")), "[0].name", "Alice"),
+ Arguments.of(Map.of("name", "Alice"), "['name']", "Alice"),
+ Arguments.of(Map.of("a,b", "Alice"), "a,b", "Alice"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "",
+ ".",
+ ".person",
+ "person.",
+ "person..name",
+ "person.[0]",
+ "persons[]",
+ "persons[",
+ "persons[0",
+ "persons[0]]",
+ "persons[-1]",
+ "persons[100]",
+ "persons[2147483648]",
+ "persons[0]name",
+ "persons[0].",
+ "persons[[0]]",
+ "attributes['name]",
+ "attributes['name'",
+ "attributes['unfinished\\",
+ "attributes['name']name",
+ "attributes[a'b'c]",
+ "attributes[unknown]",
+ "missing.name",
+ "missing[0]",
+ "person.unknown",
+ "unknown"
+ })
+ void shouldReturnNullForInvalidOrUnresolvedPath(final String path) {
+ var result = Fields.Safe.getByPath(data, path);
+
+ assertNull(result);
}
}
diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
index 895219fc..1763afa1 100644
--- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
+++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
@@ -15,9 +15,13 @@
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.List;
+import java.util.Map;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Test class for {@link Fields.Safe#getByPaths(Object, String...)} and {@link Fields.Safe#getByPaths(Object, String)}.
@@ -26,121 +30,127 @@
*/
class FieldsSafeGetByPathsTest {
- private static final String TEST_STRING = "testString";
-
- public static class A {
- public String x;
+ private record Person(String name) {
+ // empty
}
- public static class B {
- public A a;
- }
+ @SuppressWarnings("unused")
+ private static final class Data {
- @Test
- void shouldGetFieldByPaths() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
+ private final Person person = new Person("Alice");
- String x = Fields.Safe.getByPaths(b, "x.y,a.x");
+ private final List persons = List.of(new Person("Alice"));
- assertThat(x, equalTo(TEST_STRING));
- }
+ private final Object missing = null;
- @Test
- void shouldGetFieldByPathsWhenCommaSeparatedPathsHaveWhitespace() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
+ private final Map attributes = Map.of("a,b", "commaKey");
- String x = Fields.Safe.getByPaths(b, "x.y , a.x");
+ private final Map keyed = Map.of("a,b", new Person("commaKey"));
+ }
- assertThat(x, equalTo(TEST_STRING));
+ private final Data data = new Data();
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "person.name",
+ "unknown,person.name",
+ "missing.name,person.name",
+ "missing[0].name,person.name",
+ "persons[100].name,person.name",
+ "unknown, persons[0].name",
+ ",,,person.name,,,",
+ " , , person.name , ",
+ "attributes['unknown,key'],person.name",
+ "unknown , person.name",
+ ".bad,attributes[],person.name",
+ "attributes['missing\\\\'].name,person.name",
+ "attributes[foo[bar]],person.name",
+ "attributes[foo['a,b']],person.name",
+ "attributes[a'b'c],person.name",
+ "person.name] [skip],person.name",
+ "person.name] [foo[bar]],person.name"
+ })
+ void shouldResolveFirstNonNullPath(final String paths) {
+ var result = Fields.Safe.getByPaths(data, paths);
+
+ assertThat(result, equalTo("Alice"));
}
@Test
- void shouldGetFieldByPathsWithVarargs() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
-
- String x = Fields.Safe.getByPaths(b, "x.y", "a.x");
+ void shouldResolveFirstNonNullPathWithVarargs() {
+ var result = Fields.Safe.getByPaths(data, "unknown", "person.name");
- assertThat(x, equalTo(TEST_STRING));
+ assertThat(result, equalTo("Alice"));
}
@Test
- void shouldGetFieldByPathsAtFirstLevel() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
-
- A result = Fields.Safe.getByPaths(b, "a");
+ void shouldResolveFieldAtFirstLevel() {
+ var result = Fields.Safe.getByPaths(data, "person");
- assertThat(result, equalTo(a));
+ assertThat(result, equalTo(data.person));
}
- @Test
- void shouldReturnNullIfFieldDoesNotExist() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
-
- A result = Fields.Safe.getByPaths(b, "z");
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "",
+ " , , ",
+ "unknown",
+ "missing.name",
+ "persons[100].name",
+ "person.name] trailing"
+ })
+ void shouldReturnNullWhenNoPathResolves(final String paths) {
+ var result = Fields.Safe.getByPaths(data, paths);
assertThat(result, nullValue());
}
@Test
- void shouldThrowWhenCommaSeparatedPathsAreNull() {
- B b = new B();
+ void shouldReturnNullWhenCommaSeparatedPathsAreNull() {
+ var result = Fields.Safe.getByPaths(data, (String) null);
- ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, (String) null));
- assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null"));
+ assertThat(result, nullValue());
}
@Test
- void shouldReturnNullForEmptySearch() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
-
- A result = Fields.Safe.getByPaths(b, "");
+ void shouldReturnNullForEmptyVarargs() {
+ var result = Fields.Safe.getByPaths(data, new String[] { });
assertThat(result, nullValue());
+ }
- result = Fields.Safe.getByPaths(b, new String[] { });
+ @Test
+ void shouldSkipNullPathInVarargs() {
+ var result = Fields.Safe.getByPaths(data, null, "person.name");
- assertThat(result, nullValue());
+ assertThat(result, equalTo("Alice"));
+ }
- result = Fields.Safe.getByPaths(b, " , , ");
+ @Test
+ void shouldReturnNullWhenPathsArrayIsNull() {
+ var result = Fields.Safe.getByPaths(data, (String[]) null);
assertThat(result, nullValue());
}
@Test
- void shouldThrowWhenAPathIsNull() {
- A a = new A();
- a.x = TEST_STRING;
- B b = new B();
- b.a = a;
-
- ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, new String[] { null }));
- assertThat(e.getMessage(), equalTo("Cannot resolve field path: path is null"));
+ void shouldReturnNullWhenOnlyPathIsNull() {
+ var result = Fields.Safe.getByPaths(data, new String[] { null });
+
+ assertThat(result, nullValue());
}
- @Test
- void shouldThrowWhenPathsArrayIsNull() {
- B b = new B();
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "attributes['a,b'],person.name",
+ "keyed['a,b'].name,person.name"
+ })
+ void shouldNotSplitOnCommaInsideBrackets(final String paths) {
+ var result = Fields.Safe.getByPaths(data, paths);
- ReflectionException e = assertThrows(ReflectionException.class, () -> Fields.Safe.getByPaths(b, (String[]) null));
- assertThat(e.getMessage(), equalTo("Cannot resolve field paths: paths are null"));
+ assertThat(result, equalTo("commaKey"));
}
-
}
diff --git a/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java
new file mode 100644
index 00000000..73ecb204
--- /dev/null
+++ b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathTest.java
@@ -0,0 +1,175 @@
+/*
+ * 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 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;
+
+/**
+ * Test class for {@link Fields.Unchecked#getByPath(Object, String)}.
+ *
+ * @author Radu Sebastian LAZIN
+ */
+class FieldsUncheckedGetByPathTest {
+
+ 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();
+
+ @Test
+ void shouldResolvePath() {
+ var result = Fields.Unchecked.getByPath(Map.of("name", "Alice"), "name");
+
+ assertThat(result, equalTo("Alice"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("nullInputs")
+ void shouldReturnNullForNullInput(final Object root, final String path) {
+ var result = Fields.Unchecked.getByPath(root, path);
+
+ assertThat(result, nullValue());
+ }
+
+ private static Stream nullInputs() {
+ return Stream.of(
+ Arguments.of((Object) null, "name"),
+ Arguments.of(Map.of("name", "Alice"), (String) null));
+ }
+
+ @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 = Fields.Unchecked.getByPath(root, path);
+
+ assertThat(path, result, nullValue());
+ }
+
+ @ParameterizedTest
+ @MethodSource("singlePaths")
+ void shouldResolveSinglePath(final String path, final String expected) {
+ var result = Fields.Unchecked.getByPath(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 = Fields.Unchecked.getByPath(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 = Fields.Unchecked.getByPath(null, "entries[0]");
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldResolveTerminalListElement() {
+ var result = Fields.Unchecked.getByPath(root, "items[0]");
+
+ assertThat(result, equalTo(root.items.get(0)));
+ }
+}
diff --git a/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java
new file mode 100644
index 00000000..527075a6
--- /dev/null
+++ b/src/test/java/org/morphix/reflection/FieldsUncheckedGetByPathsTest.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2026 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+package org.morphix.reflection;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Test class for
+ *
+ * - {@link Fields.Unchecked#getByPaths(Object, String)}
+ * - {@link Fields.Unchecked#getByPaths(Object, String...)}
+ *
+ *
+ * @author Radu Sebastian LAZIN
+ */
+class FieldsUncheckedGetByPathsTest {
+
+ private final FieldsUncheckedGetByPathTest.WithContainers root = new FieldsUncheckedGetByPathTest.WithContainers();
+
+ @Test
+ void shouldResolveFirstPathFromCommaSeparatedAlternatives() {
+ var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), "unknown,name");
+
+ assertThat(result, equalTo("Alice"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("nullInputs")
+ void shouldReturnNullForNullInput(final Object root, final String paths) {
+ var result = Fields.Unchecked.getByPaths(root, paths);
+
+ assertThat(result, nullValue());
+ }
+
+ private static Stream nullInputs() {
+ return Stream.of(
+ Arguments.of((Object) null, "name"),
+ Arguments.of(Map.of("name", "Alice"), (String) null));
+ }
+
+ @Test
+ void shouldResolveFirstNonNullVarargsPath() {
+ var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), "unknown", null, "name");
+
+ assertThat(result, equalTo("Alice"));
+ }
+
+ @Test
+ void shouldReturnNullForEmptyVarargs() {
+ var result = Fields.Unchecked.getByPaths(Map.of("name", "Alice"), new String[] { });
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldThrowForNullVarargsArray() {
+ assertThrows(NullPointerException.class, () -> Fields.Unchecked.getByPaths(Map.of("name", "Alice"), (String[]) null));
+ }
+
+ @ParameterizedTest
+ @MethodSource("alternativePaths")
+ void shouldResolveFirstMatchingAlternative(final String paths, final String expected) {
+ var result = Fields.Unchecked.getByPaths(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 = Fields.Unchecked.getByPaths(root, paths);
+
+ assertThat(result, nullValue());
+ }
+}
diff --git a/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java b/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java
index fc7e8e74..5d2a50bf 100644
--- a/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java
+++ b/src/test/java/org/morphix/reflection/MethodsUncheckedGetAllDeclaredTest.java
@@ -85,6 +85,11 @@ void shouldThrowNullPointerExceptionForNullClassWithPredicate() {
@Test
void shouldThrowNullPointerExceptionForNullPredicate() {
+ assertThrows(NullPointerException.class, () -> Methods.Unchecked.getAllDeclared(A.class, null));
+ }
+
+ @Test
+ void shouldThrowNullPointerExceptionForNullPredicateAndNoMethods() {
assertThrows(NullPointerException.class, () -> Methods.Unchecked.getAllDeclared(C.class, null));
}