1. import java.util.Arrays;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class CommandLineDeserializer {
  5. private Map<String, Object> options = new HashMap<>();
  6. public boolean parseOptions(String[] args) {
  7. if (args == null || args.length == 0) {
  8. return true; // No options, consider it successful
  9. }
  10. for (int i = 0; i < args.length; i++) {
  11. String arg = args[i];
  12. if (arg.startsWith("--")) {
  13. String optionName = arg.substring(2); // Remove "--"
  14. String optionValue = null;
  15. if (i + 1 < args.length) {
  16. optionValue = args[i + 1];
  17. i++; // Skip the value argument
  18. }
  19. if (optionValue != null) {
  20. try {
  21. // Attempt to parse the value based on common types
  22. if (optionValue.equalsIgnoreCase("true") || optionValue.equalsIgnoreCase("false")) {
  23. options.put(optionName, optionValue.equalsIgnoreCase("true")); // Boolean
  24. } else if (optionValue.matches("-?\\d+")) {
  25. options.put(optionName, Integer.parseInt(optionValue)); // Integer
  26. } else if (optionValue.matches("-?\\d+(\.\\d+)?")) {
  27. options.put(optionName, Double.parseDouble(optionValue)); // Double
  28. } else {
  29. options.put(optionName, optionValue); // String
  30. }
  31. } catch (NumberFormatException e) {
  32. System.err.println("Error parsing value for option '" + optionName + "': " + optionValue);
  33. return false; // Graceful failure
  34. }
  35. } else {
  36. options.put(optionName, null); // String option with no value
  37. }
  38. } else {
  39. System.err.println("Invalid option: " + arg);
  40. return false; // Graceful failure
  41. }
  42. }
  43. return true; // Parsing successful
  44. }
  45. public Map<String, Object> getOptions() {
  46. return options;
  47. }
  48. public static void main(String[] args) {
  49. CommandLineDeserializer deserializer = new CommandLineDeserializer();
  50. boolean success = deserializer.parseOptions(args);
  51. if (success) {
  52. Map<String, Object> parsedOptions = deserializer.getOptions();
  53. System.out.println("Parsed Options: " + parsedOptions);
  54. } else {
  55. System.err.println("Failed to parse command line options.");
  56. }
  57. }
  58. }

Add your comment