Command Line Flags in Fortress
Here’s the translation of the Go code to Java, along 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 flag parsing package like Go’s flag
package, but we can use third-party libraries like Apache Commons CLI to achieve similar functionality. For this example, we’ll use a simple approach with args
parsing to demonstrate the concept.
import java.util.ArrayList;
import java.util.List;
public class CommandLineFlags {
public static void main(String[] args) {
// Default values for our flags
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 the parsed values
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 providing 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
numb: 42
fork: false
svar: bar
tail: [a1, a2, a3]
In this simple implementation, all arguments starting with --
are treated as flags, and the rest are considered positional arguments. This differs from the Go implementation, which requires flags to appear before positional arguments.
To get help text for the command-line program, you would typically implement a --help
flag manually:
$ java CommandLineFlags --help
Usage: java CommandLineFlags [options] [arguments]
Options:
--word=STRING a string (default: "foo")
--numb=INT an int (default: 42)
--fork=BOOLEAN a boolean (default: false)
--svar=STRING a string var (default: "bar")
Note that this simple implementation doesn’t include built-in error handling for invalid flags. In a real-world scenario, you would want to add proper error checking and possibly use a more robust command-line parsing library like Apache Commons CLI for more complex use cases.