Note that there are some explanatory texts on larger screens.

plurals
  1. POEnums shared static look-up method
    text
    copied!<p>I have the following Enum:</p> <pre><code>public enum MyEnum{ A(10, "First"), // B(20, "Second"), // C(35, "Other options"); private Integer code; private String description; private MyEnum(Integer code, String description) { this.code = code; this.description = description; } public Integer getCode() { return code; } public String getDescription() { return description; } public static MyEnum getValueOf(Integer code) { for (MyEnum e : MyEnum.values()) { if (e.getCode().equals(code)) { return e; } } throw new IllegalArgumentException("No enum const " + MyEnum.class.getName() + " for code \'" + code + "\'"); } } </code></pre> <p>Which works fine. The <code>getValueOf</code>-method exists because when communicating with an external partner, we only get the code (they chose) to map to. I need the description because I need to show a meaningfull phrase in the GUI.</p> <p>But I now have a number of similar enum classes. All having their own code &amp; description, and they need the same lookup functionality. I wanted the <code>getValueOf</code>-method to be generic so I don't need to support 30+ different enums for basically the same method.</p> <p>To solve this I wanted to make an abstract class to define this method and implement some of the common logic but this is impossible because I can't extend <code>Enum</code>.</p> <p>Then I tried to make a Utility class with the following method:</p> <pre><code>public static &lt;T extends Enum&lt;T&gt;&gt; T getValueOf(Enum&lt;T&gt; type, Integer code) {...} </code></pre> <p>But generics with Enums are confusing and I don't understand how to get this working.</p> <p>Basically what I want to know is: What is a good approach to define a common utility to an enum?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload