Skip to content

Commit

Permalink
Add @name support for Kotlin value object binding
Browse files Browse the repository at this point in the history
Fixes gh-24379
  • Loading branch information
scottfrederick committed Dec 8, 2020
1 parent dc9cdb7 commit d61724a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Expand Up @@ -48,6 +48,7 @@
* @author Madhura Bhave
* @author Stephane Nicoll
* @author Phillip Webb
* @author Scott Frederick
*/
class ValueObjectBinder implements DataObjectBinder {

Expand Down Expand Up @@ -202,7 +203,7 @@ private List<ConstructorParameter> parseConstructorParameters(KFunction<T> kotli
List<KParameter> parameters = kotlinConstructor.getParameters();
List<ConstructorParameter> result = new ArrayList<>(parameters.size());
for (KParameter parameter : parameters) {
String name = parameter.getName();
String name = getParameterName(parameter);
ResolvableType parameterType = ResolvableType
.forType(ReflectJvmMapping.getJavaType(parameter.getType()), type);
Annotation[] annotations = parameter.getAnnotations().toArray(new Annotation[0]);
Expand All @@ -211,6 +212,11 @@ private List<ConstructorParameter> parseConstructorParameters(KFunction<T> kotli
return Collections.unmodifiableList(result);
}

private String getParameterName(KParameter parameter) {
return parameter.getAnnotations().stream().filter(Name.class::isInstance).findFirst().map(Name.class::cast)
.map(Name::value).orElse(parameter.getName());
}

@Override
List<ConstructorParameter> getConstructorParameters() {
return this.constructorParameters;
Expand Down
Expand Up @@ -10,6 +10,7 @@ import org.springframework.core.ResolvableType
* Tests for `ConstructorParametersBinder`.
*
* @author Stephane Nicoll
* @author Scott Frederick
*/
class KotlinConstructorParametersBinderTests {

Expand Down Expand Up @@ -187,6 +188,15 @@ class KotlinConstructorParametersBinderTests {
assertThat(bean.value.get("bar")).isEqualTo("baz");
}

@Test
fun `Bind to named constructor parameter`() {
val source = MockConfigurationPropertySource()
source.put("foo.string-value", "test")
val binder = Binder(source)
val bean = binder.bind("foo", Bindable.of(ExampleNamedParameterBean::class.java)).get()
assertThat(bean.stringDataValue).isEqualTo("test")
}

class ExampleValueBean(val intValue: Int?, val longValue: Long?,
val booleanValue: Boolean?, val stringValue: String?,
val enumValue: ExampleEnum?)
Expand Down Expand Up @@ -228,6 +238,8 @@ class KotlinConstructorParametersBinderTests {
val stringValue: String = "my data",
val enumValue: ExampleEnum = ExampleEnum.BAR_BAZ)

data class ExampleNamedParameterBean(@Name("stringValue") val stringDataValue: String)

data class GenericValue<T>(
val value: T
)
Expand Down

0 comments on commit d61724a

Please sign in to comment.