Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing instanceof with Java Enums
    text
    copied!<p>I have a situation where I'm receiving an <code>enum</code> from an external system, and for which I need to return an <code>enum</code> of our own. The two enums have the exact same literal values in them:</p> <pre><code>// externalEnum is guaranteed not to be null public static MyEnum enumToEnum(final Enum&lt;? extends Enum&lt;?&gt;&gt; externalEnum) { if( externalEnum instanceof MyEnum ) { return (MyEnum)enumType; } else { return MyEnum.valueOf(externalEnum.name()); } } </code></pre> <p>However, the compiler squeals the following:</p> <pre> [javac] found : java.lang.Enum&lt;capture#117 of ? extends java.lang.Enum&lt;?&gt;&gt; [javac] required: myEnum [javac] if( externalEnum instanceof MyEnum ) </pre> <p>I got a version of that function that works by simply returning <code>MyEnum.valueOf(externalEnum.name())</code> - it works and that's all that matters. However, I'm baffled about the compiler error. </p> <p>I'm trying to understand the reification process of generics in this case. An instance of <code>Enum&lt;? extends Enum&lt;?&gt;&gt;</code> or simply <code>Enum&lt;?&gt;</code> can be a <code>MyEnum</code> (given that the later can never be anything other than a subtype of the former.) </p> <p>So the <code>instanceof</code> test should work, but there seems to be something in the generic definition of <code>Enum</code> (and perhaps the fact that Enums cannot be extended) that causes the compiler to puke with that particular statement.</p> <p>The workaround for me is easy, but I like to understand the problems well, and any insight on this will be appreciated.</p> <ul> <li>Luis.</li> </ul>
 

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