Spring SimpleCommandLineArgsParser

  • Author: HuiFer
  • 源码阅读仓库: SourceHot-spring

  • 类全路径: `org.springframework.core.env.SimpleCommandLineArgsParser

  • 类作用: 将命令行参数解析成 org.springframework.core.env.CommandLineArgs

  • 完整代码如下.

  1. class SimpleCommandLineArgsParser {
  2. /**
  3. * Parse the given {@code String} array based on the rules described {@linkplain
  4. * SimpleCommandLineArgsParser above}, returning a fully-populated
  5. * {@link CommandLineArgs} object.
  6. * @param args command line arguments, typically from a {@code main()} method
  7. */
  8. public CommandLineArgs parse(String... args) {
  9. CommandLineArgs commandLineArgs = new CommandLineArgs();
  10. for (String arg : args) {
  11. if (arg.startsWith("--")) {
  12. String optionText = arg.substring(2, arg.length());
  13. String optionName;
  14. String optionValue = null;
  15. if (optionText.contains("=")) {
  16. optionName = optionText.substring(0, optionText.indexOf('='));
  17. optionValue = optionText.substring(optionText.indexOf('=') + 1, optionText.length());
  18. }
  19. else {
  20. optionName = optionText;
  21. }
  22. if (optionName.isEmpty() || (optionValue != null && optionValue.isEmpty())) {
  23. throw new IllegalArgumentException("Invalid argument syntax: " + arg);
  24. }
  25. commandLineArgs.addOptionArg(optionName, optionValue);
  26. }
  27. else {
  28. commandLineArgs.addNonOptionArg(arg);
  29. }
  30. }
  31. return commandLineArgs;
  32. }
  33. }
  • 处理流程
    1. 循环命令行参数列表
    2. 去掉 --= 获取参数名称和参数值放入结果集合