I have an enum with descriptions as String. This is the enum.
public enum tabs
{
A("Actual data"),
B("Bad data"),
C("Can data"),
D("Direct data");
private String description;
tabs(String desc)
{
this.description = desc;
}
public String getDescription()
{
return this.description;
}
}
Now, if I need the data for A, I'd just do
tabs.A.description
I am in the process of creating a generic method to return the values.
I have managed to utilize the below generic method to accept an enum type as the argument. It returns an array of the enum constants. But I actually want it to return an array of the values.. ie {"Actual data", "Bad data", "Can data", "Direct data"}.
public static String[] getActualTabs(Class<? extends Enum<?>> e)
{
return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}
What options do I have to achieve this?
Enum, Interfaces, and GenericsThe enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types.
An enum is a (special type of) class, so you should declare it as the return type of your method.
Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
Method Detail Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (AccessMode c : AccessMode.
You can pass a mapper Function
to map enum constants into String
s:
public static <T extends Enum<T>> String[] getActualTabs(Class<T> e, Function<? super T, String> mapper)
{
return Arrays.stream(e.getEnumConstants()).map(mapper).toArray(String[]::new);
}
Usage:
System.out.println(Arrays.toString(getActualTabs(tabs.class,tabs::getDescription)));
Output:
[Actual data, Bad data, Can data, Direct data]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With