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:
parent
3a95a7531a
commit
e95cda10ee
|
@ -257,6 +257,17 @@ public final class PropertyMapper {
|
||||||
return when(object::equals);
|
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
|
* Return a filtered version of the source that won't map values that match the
|
||||||
* given predicate.
|
* given predicate.
|
||||||
|
|
|
@ -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");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with 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);
|
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
|
@Test
|
||||||
public void whenWhenValueMatchesShouldMap() {
|
public void whenWhenValueMatchesShouldMap() {
|
||||||
String result = this.map.from(() -> "123").when("123"::equals)
|
String result = this.map.from(() -> "123").when("123"::equals)
|
||||||
|
|
Loading…
Reference in New Issue