Browse Source

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
pull/11773/merge
Stephane Nicoll 8 years ago
parent
commit
e95cda10ee
  1. 11
      spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java
  2. 14
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java

11
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java

@ -257,6 +257,17 @@ public final class PropertyMapper { @@ -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 <R> the target type
* @param target the target type to match
* @return a new filtered source instance
*/
public <R> Source<R> whenInstanceOf(Class<R> 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.

14
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java

@ -1,5 +1,5 @@ @@ -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 { @@ -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)

Loading…
Cancel
Save