Sunday, February 18, 2024

CommandLine Arguments

Here's an interesting way to check for commandline arguments. First we setup an enum that holds our commands. As you can see, I can pass in either -h or -helpK into my program. To do this we convert the values for a specific command into a HashSet and then compare the values to what was passed in. If what we passed in is in the HashSet then we return a true vlaue, otherwise we return a false value.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public enum Commands {

    HELP("-h,-help");

    private final String values;
    Commands(String values) {
        this.values = values;
    }

    public String getValues() {
        return this.values;
    }

    public Set<String> getValuesAsArray() {
        return new HashSet<>(Arrays.asList(this.getValues().split(",")));
    }

    public boolean isSelected(String[] args) {
        for (String arg : args) {
            if (getValuesAsArray().contains(arg)) {
                return true;
            }
        }
        return false;
    }
}

In our main method of the program, we can check for values like this:

public class Main {

    public static void main(String[] args) {
        if (Commands.HELP.isSelected(args)) {
            System.out.println("Help");
        }
    }
}

At which point we perform whatever code we need to perform on it. There is a way to pass in parameters to the arguments that we are passing to the program too. But that's another story altogether.

I'm not saying this is the perfect or correct way of doing this, but it is a way of doing this for sure.

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...