Pass enum type as parameter - java

I want to create a method, that:
Takes the type of an enum and a String as arguments
The String is the name of one specific enum instance
Returns the enum instance that fits that name.
What I have tried:
In class TestUtil.java:
public static <E extends Enum<E>> E mapToEnum(Enum<E> mappingEnum, String data) {
return mappingEnum.valueOf(E, data); // Not working, needs Class of Enum and String value
}
The enum:
public enum TestEnum {
TEST1("A"),
TEST2("B");
private String value;
private TestEnum(String value) {
this.value = value;
}
}
How it should work (For example in main method):
TestEnum x = TestUtil.mapToEnum(TestEnum.class, "TEST1"); // TEST1 is the name of the first enum instance
The problem is, that I can't figure out what I need to pass into the mapToEnum method, so that I can get the valueOf from that Enum.

If the code you provided is acceptable:
public static <E extends Enum<E>> E mapToEnum(Enum<E> mappingEnum, String data) {
return mappingEnum.valueOf(E, data); // Not working, needs Class of Enum and String value
}
Then all you have to do is fix it.
Here's the code I tested:
static <T extends Enum<T>> T mapToEnum(Class<T> mappingEnum, String data) {
return Enum.valueOf(mappingEnum, data);
}
Usage:
#Test
public void test() {
TestEnum myEnum = mapToEnum(TestEnum.class, "TEST1");
System.out.println(myEnum.value); //prints "A"
}

Strongly suggest using Apache commons-lang library for boiler plate function like this ...
TestEnum x = EnumUtils.getEnum(TestEnum.class, "TEST1");
... which is exactly the code #Fenio demonstrates but handles null or wrong input with a null instead of throwing an Exception.
If you didn't know about this then check out what the rest of the lang3 library holds. I view it as a de-facto standard, saving millions of devs from re-writing minor plumbing utilities.

This is how you can iterate the enum class value and match with the parameter you have passed in the method, please check the below-mentioned code.
enum TestEnum {
TEST1("test1"),
TEST2("test2");
private String value;
private TestEnum(String value) {
this.value = value;
}
public String getName() {
return value;
}
public static TestEnum mapToEnum(String data) {
for (TestEnum userType : TestEnum.values()) {
if (userType.getName().equals(data)) {
return userType;
}
}
return null;
}
}

Related

Java enum reverse lookup

So I have this enum that doesn't work as I expected and need some modifications:
public enum MyEnum {
CODE000("text description comes here"),
private final String value;
private static final Map<String, MyEnum> LOOKUP = Maps.uniqueIndex(
Arrays.asList(MyEnum.values()),
MyEnum::getValue
);
MyEnum(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static MyEnum fromStatus(String status) {
return LOOKUP.get(status);
}
}
The way it works now is:
MyEnum.fromStatus("text description comes here") and of course I want the other way around:
MyEnum.fromStatus("CODE000") to return me "text description comes here"
Can someone suggest how I can change this ?
What you need is a literal lookup, which you get by calling valueOf:
MyEnum code000 = MyEnum.valueOf("CODE000");
And then:
String val = code000.getValue();
Please note that an exception will be raised if the string passed to valueOf doesn't resolve to an enum literal in MyEnum.
Your key function (MyEnum::getValue) is wrong as it returns the value.
It must be MyEnum::name
This will return the enum and not the text description as the value of the map is of type MyEnum. You can get the text value by calling getValue on the enum OR you can store the value in the map instead of the enum
If you want to get an enum value by enum name you can use this function :
public static String fromStatus(String status) {
MyEnum myEnum = valueOf(status);
return myEnum.getValue();
}
The answers so far are using the method valueOf. This method will return the enum constant as long as you provide a name of an enum constant. Otherwise an IllegalArgumentException will be thrown.
In your question you're using a lookup map. The Map (it looks like as it's created by Guava Maps) will return for non-enum-constant-names null. It will not throw a IllegalArgumentException in such cases. So it is a different behaviour.
In addition you say: "and of course I want the other way around"
This means you want to get the enum by status and the status by an enums name.
Therefore you would need to have two lookup methods:
status -> enum
name -> status
But you would get a compile time error if you define the two methods you mentioned:
public static MyEnum fromStatus(String status) { ... }
public static String fromStatus(String name) { ... }
The compiler could not distinguish the methods by name and parameter. But even though you wrote MyEnum.fromStatus("CODE000") actually it's the enum constant name you are using as parameter. So let's resolve the naming conflict by calling the second method fromName. The code for MyEnum could look like this:
public enum MyEnum {
CODE000("text description comes here");
private final String value;
private static final Map<String, MyEnum> LOOKUP_ENUM = Maps.uniqueIndex(Arrays.asList(MyEnum.values()), MyEnum::getValue);
private static final Map<String, String> LOOKUP_STATUS = Arrays.stream(MyEnum.values()).collect(Collectors.toMap(MyEnum::name, MyEnum::getValue));
MyEnum(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static MyEnum fromStatus(String status) {
return LOOKUP_ENUM.get(status);
}
public static String fromName(String name) {
return LOOKUP_STATUS.get(name);
}
}
If you want to lookup the enum constants by it's names in the same manner (no exception on non-enum-constant-names), you need a third map and a third lookup method:
private static final Map<String, MyEnum> LOOKUP = Maps.uniqueIndex(Arrays.asList(MyEnum.values()), MyEnum::name);
public static MyEnum byName(String name) {
return LOOKUP.get(name);
}
This would work as follows:
System.out.println(MyEnum.fromStatus("text description comes here")); // CODE000
System.out.println(MyEnum.fromStatus("invalid")); // null - no exception
System.out.println(MyEnum.fromStatus(null)); // null - no exception
System.out.println(MyEnum.fromName("CODE000")); // "text description comes here"
System.out.println(MyEnum.fromName("invalid")); // null - no exception
System.out.println(MyEnum.fromName(null)); // null - no exception
System.out.println(MyEnum.byName("CODE000")); // CODE000
System.out.println(MyEnum.byName("invalid")); // null - no exception
System.out.println(MyEnum.byName(null)); // null - no exception
If you need the byName method I would suggest to rename the methodfromName to something like statusByName to keep them comprehensible apart.
Finally one more suggestion:
Since the lookup methods may return null we could return Optional<String> / Optional<MyEnum> as result. This would allow to immediately continue processing the result.
public static Optional<MyEnum> fromStatus(String status) { ... }
public static Optional<String> statusByName(String name) { ... }
public static Optional<MyEnum> byName(String name) { ... }

Enums support with Realm?

I'm working on an android app and Realm, and I need to create an enum attribute for one of my objects; but I discovered in this post that Realm doesn't support enum yet.
My object is like this:
public class ShuttleOption extends RealmObject {
private int Id;
private String Label;
private ShuttleTypes OriginShuttleType;
}
and my enum class (ShuttleTypes) corresponds with:
HOME = 1;
and
WORK = 2;
Can anybody suggest me how to do it?
You can use the pattern described in the issue: https://github.com/realm/realm-java/issues/776#issuecomment-190147079
Basically save it as a String in Realm and convert it going in and out:
public enum MyEnum {
FOO, BAR;
}
public class Foo extends RealmObject {
private String enumDescription;
public void saveEnum(MyEnum val) {
this.enumDescription = val.toString();
}
public MyEnum getEnum() {
return MyEnum.valueOf(enumDescription);
}
}
If you need a solution that works on Kotlin you can use the following:
open class Foo: RealmObject() {
var enum: MyEnum
get() { return MyEnum.valueOf(enumDescription) }
set(newMyEum) { enumDescription = newMyEnum.name }
private var enumDescription: String = MyEnum.FOO.name
}
MyEnum is the enum declared in #ChristianMelchior answer.
It is worth mentioning that since enum doesn't have a backing field,it won't be persisted into Realm. There is no need to use the #Ignore annotation on it
i created a Kotlin delegate, which means a little less repitition
usage:
open class SomeDbModel : RealmObject() {
#delegate:Ignore
var variableEnum: MyEnum by enum(::variable)
private var variable: String = MyEnum.Default.name
}
delegate implementation:
package com.github.ericytsang
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty
inline fun <R, reified T : Enum<T>> enum(
backingField: KMutableProperty0<Int>
) = OrdinalToEnumDelegate<R, T>(T::class, backingField)
val <T : Enum<T>> KClass<out T>.enumValues get() = java.enumConstants!!.toList()
class StringToEnumDelegate<R, T : Enum<T>>(
/**
* enum class to convert the ordinal values in [backingField] to.
*/
enumClass: KClass<T>,
/**
* the property containing [T]'s ordinal value.
*/
private val backingField: KMutableProperty0<String>
) : ReadWriteProperty<R, T> {
private val enumValues = enumClass.enumValues.associateBy { it.name }
override fun getValue(thisRef: R, property: KProperty<*>): T {
return enumValues[backingField.get()]
?: error("no corresponding enum found for ${backingField.get()} in ${enumValues.keys}")
}
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
backingField.set(value.name)
}
}

How to enable enum inheritance

I'm writing a library, which has a predefined set of values for an enum.
Let say, my enum looks as below.
public enum EnumClass {
FIRST("first"),
SECOND("second"),
THIRD("third");
private String httpMethodType;
}
Now the client, who is using this library may need to add few more values. Let say, the client needs to add CUSTOM_FIRST and CUSTOM_SECOND. This is not overwriting any existing values, but makes the enum having 5 values.
After this, I should be able to use something like <? extends EnumClass> to have 5 constant possibilities.
What would be the best approach to achieve this?
You cannot have an enum extend another enum, and you cannot "add" values to an existing enum through inheritance.
However, enums can implement interfaces.
What I would do is have the original enum implement a marker interface (i.e. no method declarations), then your client could create their own enum implementing the same interface.
Then your enum values would be referred to by their common interface.
In order to strenghten the requirements, you could have your interface declare relevant methods, e.g. in your case, something in the lines of public String getHTTPMethodType();.
That would force implementing enums to provide an implementation for that method.
This setting coupled with adequate API documentation should help adding functionality in a relatively controlled way.
Self-contained example (don't mind the lazy names here)
package test;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<HTTPMethodConvertible> blah = new ArrayList<>();
blah.add(LibraryEnum.FIRST);
blah.add(ClientEnum.BLABLABLA);
for (HTTPMethodConvertible element: blah) {
System.out.println(element.getHTTPMethodType());
}
}
static interface HTTPMethodConvertible {
public String getHTTPMethodType();
}
static enum LibraryEnum implements HTTPMethodConvertible {
FIRST("first"),
SECOND("second"),
THIRD("third");
String httpMethodType;
LibraryEnum(String s) {
httpMethodType = s;
}
public String getHTTPMethodType() {
return httpMethodType;
}
}
static enum ClientEnum implements HTTPMethodConvertible {
FOO("GET"),BAR("PUT"),BLAH("OPTIONS"),MEH("DELETE"),BLABLABLA("POST");
String httpMethodType;
ClientEnum(String s){
httpMethodType = s;
}
public String getHTTPMethodType() {
return httpMethodType;
}
}
}
Output
first
POST
Enums are not extensible. To solve your problem simply
turn the enum in a class
create constants for the predefined types
if you want a replacement for Enum.valueOf: track all instances of the class in a static map
For example:
public class MyType {
private static final HashMap<String,MyType> map = new HashMap<>();
private String name;
private String httpMethodType;
// replacement for Enum.valueOf
public static MyType valueOf(String name) {
return map.get(name);
}
public MyType(String name, String httpMethodType) {
this.name = name;
this.httpMethodType = httpMethodType;
map.put(name, this);
}
// accessors
public String name() { return name; }
public String httpMethodType() { return httpMethodType; }
// predefined constants
public static final MyType FIRST = new MyType("FIRST", "first");
public static final MyType SECOND = new MyType("SECOND", "second");
...
}
Think about Enum like a final class with static final instances of itself. Of course you cannot extend final class, but you can use non-final class with static final instances in your library. You can see example of this kind of definition in JDK. Class java.util.logging.Level can be extended with class containing additional set of logging levels.
If you accept this way of implementation, your library code example can be like:
public class EnumClass {
public static final EnumClass FIRST = new EnumClass("first");
public static final EnumClass SECOND = new EnumClass("second");
public static final EnumClass THIRD = new EnumClass("third");
private String httpMethodType;
protected EnumClass(String name){
this.httpMethodType = name;
}
}
Client application can extend list of static members with inheritance:
public final class ClientEnum extends EnumClass{
public static final ClientEnum CUSTOM_FIRST = new ClientEnum("custom_first");
public static final ClientEnum CUSTOM_SECOND = new ClientEnum("custom_second");
private ClientEnum(String name){
super(name);
}
}
I think that this solution is close to what you have asked, because all static instances are visible from client class, and all of them will satisfy your generic wildcard.
We Fixed enum inheritance issue this way, hope it helps
Our App has few classes and each has few child views(nested views), in order to be able to navigate between childViews and save the currentChildview we saved them as enum inside each Class.
but we had to copy paste, some common functionality like next, previous and etc inside each enum.
To avoid that we needed a BaseEnum, we used interface as our base enum:
public interface IBaseEnum {
IBaseEnum[] getList();
int getIndex();
class Utils{
public IBaseEnum next(IBaseEnum enumItem, boolean isCycling){
int index = enumItem.getIndex();
IBaseEnum[] list = enumItem.getList();
if (index + 1 < list.length) {
return list[index + 1];
} else if(isCycling)
return list[0];
else
return null;
}
public IBaseEnum previous(IBaseEnum enumItem, boolean isCycling) {
int index = enumItem.getIndex();
IBaseEnum[] list = enumItem.getList();
IBaseEnum previous;
if (index - 1 >= 0) {
previous = list[index - 1];
}
else {
if (isCycling)
previous = list[list.length - 1];
else
previous = null;
}
return previous;
}
}
}
and this is how we used it
enum ColorEnum implements IBaseEnum {
RED,
YELLOW,
BLUE;
#Override
public IBaseEnum[] getList() {
return values();
}
#Override
public int getIndex() {
return ordinal();
}
public ColorEnum getNext(){
return (ColorEnum) new Utils().next(this,false);
}
public ColorEnum getPrevious(){
return (ColorEnum) new Utils().previous(this,false);
}
}
you could add getNext /getPrevious to the interface too
#wero's answer is very good but has some problems:
the new MyType("FIRST", "first"); will be called before map = new HashMap<>();. in other words, the map will be null when map.add() is called. unfortunately, the occurring error will be NoClassDefFound and it doesn't help to find the problem. check this:
public class Subject {
// predefined constants
public static final Subject FIRST;
public static final Subject SECOND;
private static final HashMap<String, Subject> map;
static {
map = new HashMap<>();
FIRST = new Subject("FIRST");
SECOND = new Subject("SECOND");
}
private final String name;
public Subject(String name) {
this.name = name;
map.put(name, this);
}
// replacement for Enum.valueOf
public static Subject valueOf(String name) {
return map.get(name);
}
// accessors
public String name() {
return name;
}

Access the .values() and .ordinal() method of arbitrary enum?

I would like to have a class that emulates the EnumMap, but stores int values instead of some kind of object. Now obviously you could make an EnumMap that maps to Integers, but that's a lot of autoboxing that I'd like to avoid if it's possible to do so.
So I'd like a class like this:
public class EnumIntAttributeMap
{
enum Attribute
{
Height, Weight;
}
private final int[] values;
public EnumIntAttributeMap()
{
this.values = new int[Attribute.values().length];
}
public int getValue(Attribute a)
{
return this.values[a.ordinal()];
}
public void setValue(Attribute a, int value)
{
this.values[a.ordinal()] = value;
}
}
Except I'd like to make a version that's generic across all enums. Now, since the .values() and .ordinal() methods are implicitly added by the compiler, it seems like the only way to access them would be with reflection, which would eat up the performance gains I'm trying to gain by avoiding auto-boxing, but maybe there's something I'm missing.
Any thoughts?
EDIT:
I think my initial question was unclear. I would like a class that takes (as a generic parameter) an enum, and then can use the same operations.
So I could use it with any kind of enum without needing to write the class for each kind of enum each time. Such as:
enum Attribute { Height, Weight }
enum AbilityScore {Str, Dex, Con, Int, Wis, Cha}
IdealClass<Attribute> attributeVersion;
IdealClass<AbilityScore> abilityScoreVersion;
and so on.
This is a solution:
public class EnumIntMap<E extends Enum<E>> {
private final int[] values;
public EnumIntMap(Class<E> cls)
{
this.values = new int[cls.getEnumConstants().length];
}
public int getValue(E a)
{
return this.values[a.ordinal()];
}
public void setValue(E a, int value)
{
this.values[a.ordinal()] = value;
}
}
You will have to initialize the map with the class of the enum as well.
enum Attribute { Height, Weight }
enum AbilityScore {Str, Dex, Con, Int, Wis, Cha}
EnumIntMap<Attribute> attributeVersion = new EnumIntMap(Attribute.class);
EnumIntMap<AbilityScore> abilityScoreVersion = new EnumIntMap(AbilityScore.class);
The key to doing this genetically is knowing the generic bound for an enum:
<T extends Enum<T>>
Your class can work for any enum as follows:
public class EnumIntAttributeMap<T extends Enum<T>> {
private final int[] values;
private final Class<T> clazz;
public EnumIntAttributeMap(Class<T> clazz) {
this.clazz = clazz;
this.values = new int[clazz.getEnumConstants().length];
}
public int getValue(T a) {
return this.values[a.ordinal()];
}
public void setValue(T a, int value) {
this.values[a.ordinal()] = value;
}
}
Note that the constructor requires a type token, which is required due to java's runtime type erasure.
All java Enum implicitly extend java.lang.Enum, so I think what you are looking for is:
public class EnumIntAttributeMap<E extends java.lang.Enum<E>> {
// [...]
}
Read this: Oracle's Doc on Enums.
I think you could do something that is similar to the Planets example:
public enum YourEnum{
HEIGHT (0),
WIDTH (1);
private final int index;
YourEnum(int index) {
this.index = index;
}
public int index() { return index; }
}
This is what I personally use and gives me nice standardization in the APIs
Common Interface :
public interface IValueEnum<T> {
T value();
}
Enums implement it like this:
public enum MyEnum implements IValueEnum<Integer> {
WIDTH(1),
HEIGHT(2);
private final int value;
MyEnum(int value) { this.value = value; }
#Override
public Integer value() {
return value;
}
}
Now you can get the final value by going MyEnum.WIDTH.value(), etc. Since it's using generics other enums could use Longs or Strings or what have you. It allows you to have a single simple Enum based interface in the application. It also allows you to be completely generic in your Map, etc.
EDIT: Based on New Example
public class IdealClass<T extends Enum> {
T enumValue;
public IdealClass() {
}
}

Design Issue | Enum to represent combo box options

I need to use an Enum with a combobox (values shown below).
YES (shown as YES on UI, stored in DB as Y)
NO (shown as NO on UI, stored in DB as N)
DEFAULT (shown as "" on UI, stored in DB as null)
The Enum has methods to perform the following -
toString() - to provide the custom String for UI. (showing the combo options)
OptionToDB (static) - Convert a selected option to db value (on save / update)
DBToOption (static)- Convert a DB value to selcted option (while loading the screen)
static enum EnumOption{
YES,NO,DEFAULT;
....
public static EnumOption DBToOption(String val){
if("Y".equals(val)){
return YES;
} else if("N".equals(val)){
return NO;
}else {
return DEFAULT;
}
}
....
}
It works pretty well, but the issue with above methods is that it uses if/else comparison to deduce which option / db value to be returned.
I thought of storing the dbValue as a field in enum but I was not able to reduce the if/else from DBToOption.
Can this if/else be avoided in any way using a better design??
If you store the dbValue as a field in the enum, you can remove the if/else and replace it with a for-loop, although I don't see anything wrong with those if/elses for this particular case:
static enum EnumOption {
YES("Y"),
NO("N"),
DEFAULT("");
private final String value;
private EnumOption(String value) {
this.value = value;
}
public static EnumOption DBToOption(String val) {
for (EnumOption opt : EnumOption.values()) {
if (opt.value.equals(val)) {
return opt;
}
}
return DEFAULT;
}
}
public enum EnumOption {
YES("Y"), NO("N"), DEFAULT("");
private final String value;
private final static Map<String, EnumOption> options;
static {
options = new HashMap<String, EnumOption>();
for (EnumOption opt : EnumOption.values()) {
options.put(opt.value, opt);
}
}
private EnumOption(String value) {
this.value = value;
}
public static EnumOption DBToOption(String val) {
return options.get(val) != null ? options.get(val) : DEFAULT;
}
}
And here is the test that proves it works.
public void testDBToOption() {
assertEquals(EnumOption.NO, EnumOption.DBToOption("N"));
assertEquals(EnumOption.YES, EnumOption.DBToOption("Y"));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption(""));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption(null));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption("R"));
}
So you want to get rid of the remaining if/else ...Are you doing Object Calisthenics?
You could do the following, if you do not have compatibility issues:
public enum EnumOption {
Y("Y", "YES"),
N("N", "NO"),
D("D", "");
private final String dbValue;
private final String uiValue;
private EnumOption(String dbValue, String uiValue) {
this.dbValue = dbValue;
this.uiValue = uiValue;
}
public String getDbValue() {
return this.dbValue;
}
public String uiValue() {
return this.uiValue;
}
public static EnumOption getFromDb(String dbValue) {
return EnumOption.valueOf(dbValue);
}
}
Since each enum value can only occur once, this has at least the same performance as all the other implementations.
For details about the automatically generated valueOf(String) method in enum types, and James DW's solution, you can read up in Josh Bloch's Effective Java Item 30 (Use enums instead of int constants), page 154.

Categories

Resources