简体   繁体   中英

How to pass optional arguments in java

I have a java code which makes an api call which has parameters inside it. I have passed the parameters as arguments which needed to be passed while I build the jar. I run my jar file in this way-> jarname args[0] args[1] args[2] args[3] args[4]

Now, I need a way where can I pass empty argument for PR while building the jar..is there any way possible for it?..I want PR argument to be optional.

String token = args[0];
        String ProjectName = args[1];
        String Branch = args[2];
        String Language= args[3];
                int PR = args[4];

URL IssuesTotalcountURL = new URL("sonarurl/api/issues/search?pageSize=500&componentKeys="+ProjectName+"&branch="+Branch+"&severities="+ list.get(i)+"&pullrequest=+PR+");

Maybe you can make a private method to check if is possible to retrieve the value, or get a default value, like this:

public static void main(String[] args){
        String token = getFromArgsOrDefault(args,0,"defaultToken");
        String projectName = getFromArgsOrDefault(args,1,"defaultProjectName");
        String branch = getFromArgsOrDefault(args,2,"defaultBranch");
        String language = getFromArgsOrDefault(args,3,"defaultLanguage");
        String PRString = getFromArgsOrDefault(args,4,"4");
        int PR = Integer.parseInt(PRString);

        System.out.println(token  +" "+ projectName +" "+ branch +" "+ language +" "+ PRString +" "+ PR);
    }

    private static String getFromArgsOrDefault(String[] args, int index, String defaultValue){
        if(args.length > index) {
            return args[index];
        }
        return defaultValue;
    }

You can do a null and length( isEmpty() ) check.

Example:

String PR = args[4] != null && !args[4].isEmpty() ? args[4]:"";

Or using Java 8:

String PR= Optional.ofNullable(args[4]).orElse("");

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