Search code examples
javaarraysspringargumentsprogram-entry-point

If Statement dependent on what command line arugment is passed?


My spring-boot application can be ran from the command line with arguments passed as parameters.

I want to set up my main method so that if a user passes "a" as an argument: task A is ran. If they pass "b" as an argument Task B is ran.

I currently am implementing this using:

if(args.toString().contains("a")){
//run task A
}

Is there a better way to do this / is the above implementation correct?

Full Runner class:

@Component
public class MyRunner implements CommandLineRunner {

    //other code

    @Override
    @Transactional
    public void run(String... args) throws Exception {

        if(args.toString().contains("a")){
            //run task A
        }

        if(args.toString().contains("b")){
            //run task B
        }

    }

}

Solution

  • args.toString is not what you want, it will return a toString of an array, something like: [Ljava.lang.String;@15db9742

    This would be more likely what you want:

    for(String arg : args) {
        if(arg.equals("a")) { // or .contains
            // run task A
        }
    }