Search code examples
javacommand-lineparameter-passingcommand-line-argumentsargs

How to pass args to main() in command line in Java?


I have a main function and I want to invoke getKey() method and pass 4 params via command line. How to modify code to pass params? Would you provide some suggestion?

command line looks like below:

java -Dlog4j.configuration=logging.properties -classpath ${class_path} --year="2021" --month="2" --day="2" --customerId=1234567

public static void main(String[] args) {
        
    List<String> keys = getKey(year, month, day, customerId);
    
    for (String key : keys) {
       ....
    }
}



Solution

  • How to pass args to main() in command line in Java?

    First, your command line is incorrect.

    $ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
           --year="2021" --month="2" --day="2" --customerId=1234567
    

    should be

    $ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
           ${class_name} --year="2021" --month="2" --day="2" --customerId=1234567
    

    where ${class_name} is the full name of the class containing your entry point method; e.g. com.acme.myapp.Main or something. See https://stackoverflow.com/a/18093929/139985 for more details.

    Once you have corrected the above, the args will be delivered in the args parameter as a value equivalent to:

    new String[]{"--year=2021", "--month=2", "--day=2", "--customerId=1234567"}
    

    Notice that the shell will have removed the original quotes. (If you want to stop that then they need to be quoted or escaped on command line. It happens before Java even sees the arguments.)

    It is now your problem to turn those strings into something that your program can understand. There are two approaches:

    • Implement the argument parsing in custom Java code; e.g. using String.split, Integer.parseInt and so on.

    • Find and use Java command line parser library. A Google search for java command line parser will give you a lot of candidates.

    If you want to conform to an existing set of conventions (e.g. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html), look for a library that handles this.

    (Note that the standard Java SE libraries don't include command line argument parsing functionality. I guess the reason is OS command line argument conventions are sufficiently diverse that a usable portable solution is not feasible.)