Skip to content

Commit

Permalink
Ignore default value for required parameter (#567)
Browse files Browse the repository at this point in the history
* Ignore default value for required parameter

Fix #566
  • Loading branch information
gwenn authored Aug 29, 2023
1 parent 748ddba commit 60df0cf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private void init(Object object, Parameterized parameterized, ResourceBundle bun
// Validate default values, if any and if applicable
//
if (defaultObject != null) {
if (parameterAnnotation != null) {
if (parameterAnnotation != null && !parameterAnnotation.required()) {
validateDefaultValues(parameterAnnotation.names());
}
}
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/com/beust/jcommander/JCommanderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1447,4 +1447,27 @@ class Args {
public static void main(String[] args) {
new JCommanderTest().trimTest();
}

@Test
public void ignoreDefaultValueForRequiredParameter() {
class Parameters {
@Parameter(names = "-v",
required = true,
validateValueWith = StrictlyPositiveInteger.class)
private int value;
}

String[] argv = { "-v", "1" };
Parameters args = new Parameters();
JCommander.newBuilder().addObject(args).build().parse(argv);
}
static class StrictlyPositiveInteger implements IValueValidator<Integer> {
@Override
public void validate(String name, Integer i) throws ParameterException {
if (i <= 0) {
throw new ParameterException("Parameter " + name
+ " should be strictly positive (found " + i + ")");
}
}
}
}

0 comments on commit 60df0cf

Please sign in to comment.