Skip to content

Commit

Permalink
Fixed: Default value of primitive type must not satisfy required = true
Browse files Browse the repository at this point in the history
  • Loading branch information
mkarg committed Oct 8, 2023
1 parent d4b93a6 commit a215799
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/com/beust/jcommander/JCommander.java
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,7 @@ else if (commands.isEmpty()) {
// if the parameter has a default value (not the one assigned by DefaultProvider
// but the one assigned on the variable initialization), make it as assigned and
// remove it from the list of parameters to be required
if (parameterDescription.getDefault() != null) {
if (parameterDescription.getDefault() != null && !parameterDescription.getParameterized().getType().isPrimitive()) {
fields.get(parameterDescription.getParameterized()).setAssigned(true);
requiredFields.remove(parameterDescription.getParameterized());
}
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/com/beust/jcommander/DefaultValueTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,16 @@ class MyRequiredOptsWithDefaultValues {
cmd.parse(new String[]{});
}

@Test(expectedExceptions = ParameterException.class)
public void missingRequiredPrimitiveParameterWithoutDefaultValueMustRaiseParameterException() {
class MyRequiredOptsWithDefaultValues {
@Parameter(names = "-i", required = true)
public int i; // implicit initialization value does not count as a default, so does not satisfy required = true
}

MyRequiredOptsWithDefaultValues opts = new MyRequiredOptsWithDefaultValues();
JCommander cmd = new JCommander(opts);
cmd.parse(new String[]{});
}

}

0 comments on commit a215799

Please sign in to comment.