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
This commit is contained in:
Stephane Nicoll 2018-01-26 11:03:12 +01:00
parent 3a95a7531a
commit e95cda10ee
2 changed files with 24 additions and 1 deletions

View File

@ -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.

View File

@ -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)