1. import java.util.Arrays;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class CommandLineOptions {
  5. private static Map<String, Object> options = new HashMap<>();
  6. public static void parseOptions(String[] args) {
  7. if (args == null || args.length == 0) {
  8. return; // No options provided
  9. }
  10. // Define option parsing logic with fallback for older versions
  11. for (int i = 0; i < args.length; i++) {
  12. String arg = args[i];
  13. if (arg.startsWith("-")) {
  14. String optionName = arg.substring(1); // Remove the hyphen
  15. if (options.containsKey(optionName)) {
  16. //Older versions might not support values, so we'll handle that
  17. if (i + 1 < args.length) {
  18. try {
  19. options.put(optionName, parseValue(args[i + 1]));
  20. i++; // Skip the value
  21. } catch (IllegalArgumentException e) {
  22. //Handle invalid value, e.g. log an error.
  23. System.err.println("Invalid value for option " + optionName + ": " + args[i + 1]);
  24. }
  25. } else {
  26. //Option requires a value but none was supplied
  27. options.put(optionName, true); // Default to a boolean true for missing values
  28. }
  29. } else {
  30. // Unknown option
  31. System.err.println("Unknown option: " + optionName);
  32. }
  33. } else {
  34. //Non-option arguments are ignored
  35. }
  36. }
  37. }
  38. private static Object parseValue(String value) {
  39. //Basic type conversion, add more as needed
  40. if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("1")) {
  41. return true;
  42. } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("0")) {
  43. return false;
  44. } else {
  45. try {
  46. return Integer.parseInt(value);
  47. } catch (NumberFormatException e) {
  48. try {
  49. return Double.parseDouble(value);
  50. } catch (NumberFormatException e2) {
  51. return value; //Treat as string
  52. }
  53. }
  54. }
  55. }
  56. public static Map<String, Object> getOptions() {
  57. return options;
  58. }
  59. public static void main(String[] args) {
  60. String[] commandLineArgs = {"-verbose", "-output", "data.txt", "-debug", "false", "123", "some_other_arg"};
  61. parseOptions(commandLineArgs);
  62. Map<String, Object> parsedOptions = getOptions();
  63. System.out.println(parsedOptions);
  64. }
  65. }

Add your comment