Command Line Flags in Java
Here’s the translation of the Go code to Java, with explanations in Markdown format suitable for Hugo:
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
Java doesn’t have a built-in package for parsing command-line flags, but we can use a third-party library like Apache Commons CLI. For this example, we’ll use a simple approach with args
array parsing.
import java.util.ArrayList;
import java.util.List;
public class CommandLineFlags {
public static void main(String[] args) {
// We'll use these variables to store our flag values
String word = "foo";
int numb = 42;
boolean fork = false;
String svar = "bar";
List<String> tail = new ArrayList<>();
// Parse command line arguments
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--")) {
String[] parts = arg.substring(2).split("=", 2);
if (parts.length == 2) {
switch (parts[0]) {
case "word":
word = parts[1];
break;
case "numb":
numb = Integer.parseInt(parts[1]);
break;
case "fork":
fork = Boolean.parseBoolean(parts[1]);
break;
case "svar":
svar = parts[1];
break;
}
}
} else {
tail.add(arg);
}
}
// Print out the parsed options and any trailing positional arguments
System.out.println("word: " + word);
System.out.println("numb: " + numb);
System.out.println("fork: " + fork);
System.out.println("svar: " + svar);
System.out.println("tail: " + tail);
}
}
To experiment with the command-line flags program, first compile it and then run the resulting class file directly.
$ javac CommandLineFlags.java
Try out the compiled program by giving it values for all flags:
$ java CommandLineFlags --word=opt --numb=7 --fork=true --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: []
Note that if you omit flags, they automatically take their default values:
$ java CommandLineFlags --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []
Trailing positional arguments can be provided after any flags:
$ java CommandLineFlags --word=opt a1 a2 a3
word: opt
...
tail: [a1, a2, a3]
This simple implementation doesn’t provide automatic help text generation or strict flag ordering. For more robust command-line parsing in Java, consider using libraries like Apache Commons CLI or JCommander.
Note that unlike the flag
package in Go, this simple Java implementation doesn’t enforce a specific order for flags and positional arguments. All non-flag arguments are treated as positional and added to the tail
list.
For a more feature-complete command-line parsing experience in Java, similar to Go’s flag
package, you would typically use a third-party library. These libraries often provide features like automatic help text generation, strict flag ordering, and more robust parsing options.