cbeust / jcommander

Command line parsing framework for Java
Apache License 2.0
1.96k stars 334 forks source link

Regression: NPE when using a Boolean field that has not been initialised #447

Open pvliss opened 6 years ago

pvliss commented 6 years ago

Using version 1.72, an NPE is thrown when using a field of type Boolean without initializing it.

This was working normally until version 1.60.

I have not checked against other versions

Test case

Here's a simple test case that should otherwise work:

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class TestNPE {

    public static final String PARAM_NAME = "--refresh"; //NOI18N

    @Test
    public void testBooleanWithoutDefaultValue() {
        CmdArgs args = new CmdArgs();
        JCommander commander = new JCommander(args);
        commander.setAcceptUnknownOptions(true);
        commander.parse(PARAM_NAME);

        assertTrue(args.m_refresh);
    }

    public static class CmdArgs {

        @Parameter(names = PARAM_NAME)
        private Boolean m_refresh;
    }

}

but fails with the following exception:

java.lang.NullPointerException
    at com.beust.jcommander.JCommander.parseValues(JCommander.java:718)
    at com.beust.jcommander.JCommander.parse(JCommander.java:340)
    at com.beust.jcommander.JCommander.parse(JCommander.java:319)
    at TestNPE.testBooleanWithoutDefaultValue(TestNPE.java:20)
        ...

Workarounds:

  1. Initialize field to false
  2. Switch to using boolean instead
shaburov commented 6 years ago

Error in Parameterized.get (Object object) image

mageddo commented 5 years ago

same here

shaburov commented 4 years ago

@pvliss @mageddo

<repositories>
    <repository>
        <id>spring.plugins.repository</id>
        <url>http://repo.spring.io/plugins-release/</url>
    </repository>
</repositories>

and use version 1.74+

<dependency>
    <groupId>com.beust</groupId>
    <artifactId>jcommander</artifactId>
    <version>1.74</version>
</dependency>