import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CommandLineDeserializer {
private Map<String, Object> options = new HashMap<>();
public boolean parseOptions(String[] args) {
if (args == null || args.length == 0) {
return true; // No options, consider it successful
}
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--")) {
String optionName = arg.substring(2); // Remove "--"
String optionValue = null;
if (i + 1 < args.length) {
optionValue = args[i + 1];
i++; // Skip the value argument
}
if (optionValue != null) {
try {
// Attempt to parse the value based on common types
if (optionValue.equalsIgnoreCase("true") || optionValue.equalsIgnoreCase("false")) {
options.put(optionName, optionValue.equalsIgnoreCase("true")); // Boolean
} else if (optionValue.matches("-?\\d+")) {
options.put(optionName, Integer.parseInt(optionValue)); // Integer
} else if (optionValue.matches("-?\\d+(\.\\d+)?")) {
options.put(optionName, Double.parseDouble(optionValue)); // Double
} else {
options.put(optionName, optionValue); // String
}
} catch (NumberFormatException e) {
System.err.println("Error parsing value for option '" + optionName + "': " + optionValue);
return false; // Graceful failure
}
} else {
options.put(optionName, null); // String option with no value
}
} else {
System.err.println("Invalid option: " + arg);
return false; // Graceful failure
}
}
return true; // Parsing successful
}
public Map<String, Object> getOptions() {
return options;
}
public static void main(String[] args) {
CommandLineDeserializer deserializer = new CommandLineDeserializer();
boolean success = deserializer.parseOptions(args);
if (success) {
Map<String, Object> parsedOptions = deserializer.getOptions();
System.out.println("Parsed Options: " + parsedOptions);
} else {
System.err.println("Failed to parse command line options.");
}
}
}
Add your comment