The methods / member functions valueOf
and values
that are implicitly declared in the Enum derived class
How to call generically.
Java
Suppose the following enum type is defined.
public enum PrimaryColor {
RED, GREEN, BLUE
}
public static void main(String... args) {
PrimaryColor red = PrimaryColor.valueOf("RED"); // RED
PrimaryColor[] values = PrimaryColor.values(); // [RED, GREEN, BLUE]
}
public static <E extends Enum<E>> E valueOf(Class<E> enumType, String name) {
return Enum.valueOf(enumType, name);
}
public static <E extends Enum<E>> E[] values(Class<E> enumType) {
return enumType.getEnumConstants();
}
public static void main(String... args) {
PrimaryColor red = valueOf(PrimaryColor.class, "RED"); // RED
PrimaryColor[] values = values(PrimaryColor.class); // [RED, GREEN, BLUE]
}
Kotlin
Suppose the following enum type is defined.
enum class PrimaryColor {
RED, GREEN, BLUE
}
fun main() {
val red: PrimaryColor = PrimaryColor.valueOf("RED") // RED
val values: Array<PrimaryColor> = PrimaryColor.values() // [RED, GREEN, BLUE]
}
inline fun <reified E : Enum<E>> valueOf(name: String): E =
enumValueOf<E>(name) // `<E>`Can be omitted (type inference) in this case
inline fun <reified E : Enum<E>> values(): Array<E> =
enumValues<E>() // `<E>`Can be omitted (type inference) in this case
fun main() {
val red: PrimaryColor = valueOf("RED")
val values: Array<PrimaryColor> = values()
}
/that's all
Recommended Posts