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 } } } 
2
  • i would checkout stackoverflow.com/questions/367706/… 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... Commented Apr 25, 2016 at 16:03
  • 3
    See this Java Command line arguments issue. This is a duplicate. Commented Apr 25, 2016 at 16:05

1 Answer 1

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 } } 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I got confused with, I think c++, where the first argument is the full command

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.