简体   繁体   中英

If a java program will be called from shell, which way is better to pass the arguments?

I have a java program which has long argument list:

public class MyTool {
    public static void main(String[] args) {
        String aaa = args[0];
        String bbb = args[1];
        String ccc = args[2];
        String ddd = args[3];
        String eee = args[4];
        String fff = args[5];
        String ggg = args[6];
    }
}

When my colleague use it, he complains that the argument list is too long, that he have to pass the arguments this way:

java MyTool someArg someArg someArg someArg someArg someArg someArg

that he is confused what the meaning of each argument without checking the source code again and again.

He suggest me to use -Daaa=bbb style to pass argument, that means my code should be:

public class MyTool {
    public static void main(String[] args) {
        String aaa = System.getProperty("aaa");
        String bbb = System.getProperty("bbb");
        String ccc = System.getProperty("ccc");
        String ddd = System.getProperty("ddd");
        String eee = System.getProperty("eee");
        String fff = System.getProperty("fff");
        String ggg = System.getProperty("ggg");
    }
}

So he can invoke it as:

java -Daaa=someArg -Dbbb=someArg -Dccc=someArg \
     -Dddd=someArg -Deee=someArg -Dfff=someArg -Dggg=someArg \
     MyTool

Which is much better for him to know the meanings of each argument without checking the source code.

I'm confused which way is better, and when I should use one against another?

In all honesty you should just stick to the regular passing of arguments to the main method. In my experience it's best to use the -D*argument* style when you either don't have access to the arguments via the main method or need it in multiple programs.

Edit: Also the fact that you're now setting a global property for something specific to a single project.

One or two positional parameters are ok but if you have a bunch of options you really should give them a name (meaning) and using a command line option library like this one: http://www.gnu.org/software/gnuprologjava/api/gnu/getopt/Getopt.html .

You endet up in something like this

java MyTool -xyz -a someArg --aaa=someArg --bbb=someArg --ccc=someArg

Using his way he would have to type more, but he'd also know better what he's doing. Your way is faster but a little cryptic. So its a design choice and everybody will advise differently here.

My taste would be doing it your original way - however; I'd always add a '--help' call parameter, which will print the arguments that are available, so he doesn't have to check the source code (which a user never should need to do) and things get less cryptic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM