Document null-safe index operator in SpEL

See gh-29847
This commit is contained in:
Sam Brannen
2024-03-23 14:24:29 +01:00
parent 38c473fd05
commit 218a148898
4 changed files with 88 additions and 1 deletions

View File

@@ -58,6 +58,13 @@ import org.springframework.util.ReflectionUtils;
* <li>Objects: the property with the specified name</li>
* </ul>
*
* <h3>Null-safe Indexing</h3>
*
* <p>As of Spring Framework 6.2, null-safe indexing is supported via the {@code '?.'}
* operator. For example, {@code 'colors?.[0]'} will evaluate to {@code null} if
* {@code colors} is {@code null} and will otherwise evaluate to the 0<sup>th</sup>
* color.
*
* @author Andy Clement
* @author Phillip Webb
* @author Stephane Nicoll

View File

@@ -688,6 +688,24 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(city).isNull();
}
@Test
void nullSafeIndexing() {
IEEE society = new IEEE();
EvaluationContext context = new StandardEvaluationContext(society);
// evaluates to Inventor("Nikola Tesla")
Inventor inventor = parser.parseExpression("members?.[0]") // <1>
.getValue(context, Inventor.class);
assertThat(inventor).extracting(Inventor::getName).isEqualTo("Nikola Tesla");
society.members = null;
// evaluates to null - does not throw an Exception
inventor = parser.parseExpression("members?.[0]") // <2>
.getValue(context, Inventor.class);
assertThat(inventor).isNull();
}
@Test
@SuppressWarnings("unchecked")
void nullSafeSelection() {