Skip to content

Commit faced57

Browse files
committed
ConversionUtils: add method for converting to enum
1 parent c93c0f0 commit faced57

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

‎src/main/java/org/scijava/util/ConversionUtils.java‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,30 @@ public static <T> T convert(final Object value, final Class<T> type) {
210210
}
211211
}
212212

213+
/**
214+
* Converts the given string value to an enumeration constant of the specified
215+
* type.
216+
*
217+
* @param value The value to convert.
218+
* @param type The type of the enumeration constant.
219+
* @return The converted enumeration constant, or null if the type is not an
220+
* enumeration type or has no such constant.
221+
*/
222+
public static <T> T convertToEnum(final String value, final Class<T> type) {
223+
if (value == null || !type.isEnum()) return null;
224+
try {
225+
@SuppressWarnings({ "rawtypes", "unchecked" })
226+
final Enum result = Enum.valueOf((Class) type, value);
227+
@SuppressWarnings("unchecked")
228+
final T typedResult = (T) result;
229+
return typedResult;
230+
}
231+
catch (final IllegalArgumentException exc) {
232+
// no such enum constant
233+
return null;
234+
}
235+
}
236+
213237
/**
214238
* Checks whether objects of the given class can be converted to the specified
215239
* type.

0 commit comments

Comments
 (0)