Skip to content

Commit b7454a5

Browse files
authored
Fix issue with non-Optional generic parameters in controller methods throwing an exception (#764)
* Fix issue with non-Optional generic parameters in controller methods throwing an exception
1 parent 1424b02 commit b7454a5

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

ninja-core/src/main/java/ninja/params/ControllerMethodInvoker.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,13 @@ private MethodParameter(Type genericType) {
417417
if (maybeOptional.isAssignableFrom(Optional.class)) {
418418
isOptional = true;
419419
parameterClass = getClass(parameterizedType.getActualTypeArguments()[0]);
420+
} else {
421+
// This case is necessary here for types like List<String>
422+
// because genericType is not a class in that case, so letting it fall through below throws an exception.
423+
// So we explicitly handle the case here and use parameterizedType.getRawType() as the parameterClass
424+
// (which would be List in the example above), and matches the behavior of older Ninja versions.
425+
isOptional = false;
426+
parameterClass = maybeOptional;
420427
}
421428
}
422429

ninja-core/src/test/java/ninja/params/ControllerMethodInvokerTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
import java.util.ArrayList;
5959
import java.util.Arrays;
6060
import java.util.Date;
61+
import java.util.List;
6162
import java.util.Optional;
6263

6364
import static org.junit.Assert.*;
@@ -1073,6 +1074,14 @@ public void bodyWithOptionalShouldBeEmptyIfNoBodyPresent() {
10731074
verify(mockController).bodyWithOptional(Optional.empty());
10741075
}
10751076

1077+
@Test
1078+
public void bodyWithGenericTypeShouldRun() {
1079+
List<String> body = Arrays.asList("value1", "value2");
1080+
when(context.parseBody(List.class)).thenReturn(body);
1081+
create("bodyWithGenericType").invoke(mockController, context);
1082+
verify(mockController).bodyWithGenericType(body);
1083+
}
1084+
10761085
// JSR303Validation(@Pattern(regexp = "[a-z]*") String param1,
10771086
// @Length(min = 5, max = 10) String param2, @Min(3) @Max(10) int param3);
10781087
@Test
@@ -1426,6 +1435,8 @@ public Result multiple(@Param("param1") String param1, @PathParam("param2") int
14261435
public Result badValidatorWithOptional(@Param("param1") @NumberValue(min = 10) Optional<String> param1);
14271436

14281437
public Result body(Object body);
1438+
1439+
public Result bodyWithGenericType(List<String> myList);
14291440

14301441
public Result bodyWithOptional(Optional<Object> body);
14311442

0 commit comments

Comments
 (0)