From e95cda10eec2b71016254f5bcb39825877831ec2 Mon Sep 17 00:00:00 2001 From: Stephane Nicoll Date: Fri, 26 Jan 2018 11:03:12 +0100 Subject: [PATCH] Add whenInstanceOf to PropertyMapper Add an operation on PropertyMapper that takes care of casting. Returns a source for the requested type if the current value is of the right type. Closes gh-11788 --- .../boot/context/properties/PropertyMapper.java | 11 +++++++++++ .../context/properties/PropertyMapperTests.java | 14 +++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java index 2a54a574878..1af8d667bae 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java @@ -257,6 +257,17 @@ public final class PropertyMapper { return when(object::equals); } + /** + * Return a filtered version of the source that will only map values that are an + * instance of the given type. + * @param the target type + * @param target the target type to match + * @return a new filtered source instance + */ + public Source whenInstanceOf(Class target) { + return when(target::isInstance).as(target::cast); + } + /** * Return a filtered version of the source that won't map values that match the * given predicate. diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index f8a9bf554f5..330f8ca7dca 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -142,6 +142,18 @@ public class PropertyMapperTests { this.map.from(() -> "123").whenEqualTo("321").toCall(Assert::fail); } + @Test + public void whenInstanceOfToWhenValueIsTargetTypeShouldMatch() { + Long result = this.map.from(() -> 123L).whenInstanceOf(Long.class) + .toInstance((value) -> value + 1); + assertThat(result).isEqualTo(124L); + } + + @Test + public void whenInstanceOfWhenValueIsNotTargetTypeShouldNotMatch() { + this.map.from(() -> 123).whenInstanceOf(Double.class).toCall(Assert::fail); + } + @Test public void whenWhenValueMatchesShouldMap() { String result = this.map.from(() -> "123").when("123"::equals)