Skip to content

Commit

Permalink
Fix an NPE (#579)
Browse files Browse the repository at this point in the history
When mainParameter is null (which is the default), calling
getMainParameterValue()/getMainParameterDescription() throws an NPE because it
tries to access a field on a null object.

Co-authored-by: Markus KARG <[email protected]>
  • Loading branch information
jianglai and mkarg authored Apr 11, 2024
1 parent 38acef9 commit 35e8bd6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/main/java/com/beust/jcommander/JCommander.java
Original file line number Diff line number Diff line change
Expand Up @@ -1036,8 +1036,9 @@ private void initMainParameterValue(String arg) {

public String getMainParameterDescription() {
if (descriptions == null) createDescriptions();
return mainParameter.annotation != null ? mainParameter.annotation.description()
: null;
return mainParameter == null
? null
: mainParameter.annotation != null ? mainParameter.annotation.description() : null;
}

/**
Expand Down Expand Up @@ -1322,7 +1323,7 @@ public List<ParameterDescription> getParameters() {
* @return the main parameter description or null if none is defined.
*/
public ParameterDescription getMainParameterValue() {
return mainParameter.description;
return mainParameter == null ? null : mainParameter.description;
}

private void p(String string) {
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/com/beust/jcommander/JCommanderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1438,6 +1438,20 @@ class Args {
.build();
}

@Test
public void noMainParameter() {
class Args {
@Parameter(names = "-f")
private int f;
}
Args args = new Args();
JCommander jcommander =
JCommander.newBuilder().addObject(args).args(new String[] {"-f", "1"}).build();
Assert.assertNull(jcommander.getMainParameter());
Assert.assertNull(jcommander.getMainParameterDescription());
Assert.assertNull(jcommander.getMainParameterValue());
}

@Test
public void mainWithConverter() {

Expand Down

0 comments on commit 35e8bd6

Please sign in to comment.