import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CommandLineOptions {
private static Map<String, Object> options = new HashMap<>();
public static void parseOptions(String[] args) {
if (args == null || args.length == 0) {
return; // No options provided
}
// Define option parsing logic with fallback for older versions
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-")) {
String optionName = arg.substring(1); // Remove the hyphen
if (options.containsKey(optionName)) {
//Older versions might not support values, so we'll handle that
if (i + 1 < args.length) {
try {
options.put(optionName, parseValue(args[i + 1]));
i++; // Skip the value
} catch (IllegalArgumentException e) {
//Handle invalid value, e.g. log an error.
System.err.println("Invalid value for option " + optionName + ": " + args[i + 1]);
}
} else {
//Option requires a value but none was supplied
options.put(optionName, true); // Default to a boolean true for missing values
}
} else {
// Unknown option
System.err.println("Unknown option: " + optionName);
}
} else {
//Non-option arguments are ignored
}
}
}
private static Object parseValue(String value) {
//Basic type conversion, add more as needed
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("1")) {
return true;
} else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("0")) {
return false;
} else {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
try {
return Double.parseDouble(value);
} catch (NumberFormatException e2) {
return value; //Treat as string
}
}
}
}
public static Map<String, Object> getOptions() {
return options;
}
public static void main(String[] args) {
String[] commandLineArgs = {"-verbose", "-output", "data.txt", "-debug", "false", "123", "some_other_arg"};
parseOptions(commandLineArgs);
Map<String, Object> parsedOptions = getOptions();
System.out.println(parsedOptions);
}
}
Add your comment