0

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
        }

    }

}
java123999
  • 6,974
  • 36
  • 77
  • 121
  • i would checkout http://stackoverflow.com/questions/367706/how-to-parse-command-line-arguments-in-java for better ways to parse the incoming args. because the way you are doing it will have lots of false positives. for example. what if the user passes "basket" as an argument... – karina Apr 25 '16 at 16:03
  • 3
    See this [Java Command line arguments issue](http://stackoverflow.com/questions/716153/java-command-line-arguments). This is a duplicate. – jtmingus Apr 25 '16 at 16:05

1 Answers1

4

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
    }
}
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • Note that with the enhanced-for you're not skipping *any* arguments. It's also unclear to me why you'd bother skipping the first one at all. – Makoto Apr 25 '16 at 16:09
  • 1
    I got confused with, I think c++, where the first argument is the full command – Jorn Vernee Apr 25 '16 at 16:09