0

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+");
priya
  • 391
  • 1
  • 5
  • 24
  • You can override a method such so ``public void something()``, ``public void something(int i)``, ``public void something(int i, String s)``. If the optional parameters are the same type, then you can use the ``...`` operator which is syntactic sugar for passing an array. – NomadMaker Jan 08 '21 at 12:48
  • take a look at https://stackoverflow.com/questions/42753849/java-making-an-optional-command-line-argument – JavaMan Jan 08 '21 at 12:48

2 Answers2

2

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;
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Marcos Echagüe
  • 547
  • 2
  • 8
  • 21
0

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("");
Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
  • `args[4] == null && args[4].isEmpty()` this is wrong. If it's null, it will NPE – Michael Jan 08 '21 at 13:07
  • Can be simplified to just `args[4] != null ? args[4] : ""`. Your answer implies Java 8 style is more concise, but it's only because the ternary you've chosen is inefficient – Michael Jan 08 '21 at 16:32