Skip to content

Commit

Permalink
Treat string as ordinal of enum if it's numeric
Browse files Browse the repository at this point in the history
  • Loading branch information
quaff committed Sep 22, 2023
1 parent 6b35d43 commit 3e02eca
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -25,6 +25,7 @@
*
* @author Keith Donald
* @author Stephane Nicoll
* @author Yanming Zhou
* @since 3.0
*/
@SuppressWarnings({"rawtypes", "unchecked"})
Expand All @@ -51,6 +52,10 @@ public T convert(String source) {
// It's an empty enum identifier: reset the enum value to null.
return null;
}
if (source.chars().allMatch(Character::isDigit)) {
// It's safe to use source as ordinal since name cannot be numeric.
return this.enumType.getEnumConstants()[Integer.parseInt(source)];
}
return (T) Enum.valueOf(this.enumType, source.trim());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,12 @@ void stringToEnumWithBaseInterfaceConversion() {
assertThat(conversionService.convert("base1", MyEnum.class)).isEqualTo(MyEnum.A);
}

@Test
void stringToEnumWithOrdinalAsString() {
conversionService.addConverterFactory(new StringToEnumConverterFactory());
assertThat(conversionService.convert("0", MyEnum.class)).isEqualTo(MyEnum.A);
}

@Test
void convertNullAnnotatedStringToString() throws Exception {
String source = null;
Expand Down

0 comments on commit 3e02eca

Please sign in to comment.