From dff48ad8dd579fffd4843661e41011ed9287910c Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Thu, 13 Nov 2014 11:02:50 +0100 Subject: [PATCH] Allow non-String args in JOptCommandLinePropertySource Prior to this commit, JOptCommandLinePropertySource prevented the possibility of non-String option arguments. This effectively prevents the use of JOpt's #ofType support (which allows specifying custom argument types). Now, non-String arguments are detected and converted to strings as necessary. JOpt's #ofType now works as expected. A test has been added to cover this case. --- .../core/env/JOptCommandLinePropertySource.java | 3 +-- .../env/JOptCommandLinePropertySourceTests.java | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java b/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java index 161cccd37c..b34e4b9dc4 100644 --- a/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java @@ -98,8 +98,7 @@ public class JOptCommandLinePropertySource extends CommandLinePropertySource argValues = this.source.valuesOf(name); List stringArgValues = new ArrayList(); for (Object argValue : argValues) { - Assert.isInstanceOf(String.class, argValue, "Argument values must be of type String"); - stringArgValues.add((String) argValue); + stringArgValues.add(argValue instanceof String ? (String) argValue : argValue.toString()); } if (stringArgValues.isEmpty()) { return (this.source.has(name) ? Collections.emptyList() : null); diff --git a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java index cc9c716921..00a059d3dc 100644 --- a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java @@ -159,4 +159,18 @@ public class JOptCommandLinePropertySourceTests { String nonOptionArgs = ps.getProperty("NOA"); assertThat(nonOptionArgs, equalTo("noa1,noa2")); } + + @Test + public void withRequiredArg_ofTypeEnum() { + OptionParser parser = new OptionParser(); + parser.accepts("o1").withRequiredArg().ofType(OptionEnum.class); + OptionSet options = parser.parse("--o1=VAL_1"); + + PropertySource ps = new JOptCommandLinePropertySource(options); + assertThat(ps.getProperty("o1"), equalTo("VAL_1")); + } + + public static enum OptionEnum { + VAL_1; + } }