Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Although it might be a little counter intuitive using <code>enum</code> has proven quite powerful in that regard.</p> <p>Every <code>enum</code> has a <code>valueOf(String)</code> method that returns an Element for that name. Then you may use the retrieved Element in a switch statement. The only ugly part is that <code>valueOf(String)</code> throws an <code>IllegalArgumentException</code>. So catching that is equivalent to a default case.</p> <pre><code>enum Type{ JAVA_LANG_STRING; CHAR; DECIMAL; BOOLEAN; JAVA_LANG_BIGDECIMAL; } public static SwitchType&lt;?&gt; switchT(final String typeName, final String memberName) { try{ Type t = Type.valueOf(typeName.toUppercase().replace(".","_")); switch(t){ case Type.JAVA_LANG_STRING: return new SwitchInputType&lt;String&gt;(new String(memberName + " ")); case Type.CHAR: return new SwitchInputType&lt;Character&gt;(new Character('a')); case Type.DECIMAL: case Type.JAVA_MATH_BIGDECIMAL: return new SwitchInputType&lt;BigDecimal&gt;(new BigDecimal("34.58")); }catch(IllegalArgumentException e){ //default case } } </code></pre> <p>Also enums may implement interfaces. Either by providing one implementation for each element or one global one.</p> <pre><code>interface SwitchInputTypeFacotry { SwitchInputType get(String arg); } enum TypeName implements SwitchInputTypeFacotry{ CHAR{ SwitchInputType get(String arg){ return new SwitchInputType&lt;Character&gt;(new Character('a')); } } [...] } public static SwitchType&lt;?&gt; switchT(final String typeName, final String memberName) { try{ SwitchInputTypeFacotry t = Type.valueOf(typeName.toUppercase().replace(".","_")); return t.get(memberName); }catch(IllegalArgumentException e){ //default case } } </code></pre> <p>The second way makes it very easy to extend functionality (as long as it stays in one module, subclassing is not possible with enums).</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