Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert a String to the correct Enum constant (multiple Enums implementing a common interface)?
    primarykey
    data
    text
    <p>Suppose I have an interface...</p> <pre><code>public interface Feature { public abstract void doSmth(); } </code></pre> <p>... and multiple enums implementing that interface:</p> <p>// First enum</p> <pre><code>public enum FeatureA implements Feature { A1 { @Override public void doSmth() { System.out.println("A ==== A1"); } }, A2 { @Override public void doSmth() { System.out.println("A ==== A2"); } }; @Override public abstract void doSmth(); } </code></pre> <p>//Second enum</p> <pre><code>public enum FeatureB implements Feature { B1 { @Override public void doSmth() { System.out.println("B ==== B1"); } }, B2 { @Override public void doSmth() { System.out.println("B ==== B2"); } }, B3 { @Override public void doSmth() { System.out.println("B ==== B3"); } }; @Override public abstract void doSmth(); } </code></pre> <p>// and many other enums implementing Feature</p> <p>Now suppose I assemble a set of Strings corresponding to the names of enum constants like this (this is necessary for the third party code)...</p> <pre><code>Set&lt;String&gt; singleEnum = new LinkedHashSet&lt;String&gt;(); singleEnum.add("A2"); singleEnum.add("A1"); </code></pre> <p>... and later I need to convert each String in such a set to the enum constant and then apply the doSmth() method. singleEnum contains names of FeatureA constants only, so I'm able to apply the valueOf(String) method in this case:</p> <pre><code>for (String s : singleEnum) { FeatureA.valueOf(s).doSmth(); } </code></pre> <p>But what if the Strings in the set correspond to varying enum constants? E.g.:</p> <pre><code>Set&lt;String&gt; multipleEnums = new LinkedHashSet&lt;String&gt;(); multipleEnums.add("A1"); multipleEnums.add("B2"); multipleEnums.add("A2"); </code></pre> <p>I would like to do something like this: </p> <pre><code>for (String s : multipleEnums) { Feature./* convert s to the correct enum */.doSmth(); } </code></pre> <p>Is there an easy way to do that? The only method Eclipse allows to apply to Feature is Feature.class, and I don't really know how to proceed from there. I'm dealing with huge datasets, so performance is important.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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