Skip to content

Commit ce33966

Browse files
committed
Add Mapper#toEnum(String, Class<T>)
1 parent 127ebae commit ce33966

File tree

1 file changed

+15
-0
lines changed
  • src/main/java/xyz/srnyx/javautilities/manipulation

1 file changed

+15
-0
lines changed

src/main/java/xyz/srnyx/javautilities/manipulation/Mapper.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,21 @@ public static Optional<UUID> toUUID(@Nullable Object object) {
7676
return object == null ? Optional.empty() : MiscUtility.handleException(() -> UUID.fromString(object.toString()), IllegalArgumentException.class);
7777
}
7878

79+
/**
80+
* Converts a {@link String} to an {@link Enum} value of the specified class
81+
*
82+
* @param name the name of the {@link Enum} value to convert
83+
* @param enumClass the {@link Class} of the {@link Enum} to convert to
84+
*
85+
* @return an {@link Optional} containing the {@link Enum} value if it exists, otherwise {@link Optional#empty()}
86+
*
87+
* @param <T> the type of the {@link Enum}
88+
*/
89+
@NotNull
90+
public static <T extends Enum<T>> Optional<T> toEnum(@Nullable String name, @NotNull Class<T> enumClass) {
91+
return name == null || name.isEmpty() ? Optional.empty() : MiscUtility.handleException(() -> Enum.valueOf(enumClass, name.toUpperCase()), IllegalArgumentException.class);
92+
}
93+
7994
private Mapper() {
8095
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
8196
}

0 commit comments

Comments
 (0)