Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You'll need to use a generic helper method with an unchecked cast:</p> <pre><code>private static &lt;T extends Enum&lt;T&gt; &amp; Marshallable&gt; void fooHelper(Class&lt;? extends Marshallable&gt; type) { if (type.isEnum()) { //This is safe because of the isEnum check, and we don't return any //type with T (important because the caller can specify what T is). @SuppressWarnings("unchecked") final Class&lt;T&gt; enumType = (Class&lt;T&gt;)type; final List&lt;T&gt; enumConstants = Arrays.asList(enumType.getEnumConstants()); foo(enumConstants); } } </code></pre> <p>The reason your version doesn't work is because with <code>T extends Enum&lt;T&gt; &amp; Marshallable</code>, <code>T</code> is recursively bound - something that can only be expressed with type parameters. The wildcard type arguments in <code>? extends Enum&lt;? extends Marshallable&gt;</code> no longer specify that relationship.</p> <p><strong>WARNING:</strong> It's imperative that <code>fooHelper</code> doesn't return a type containing <code>T</code> because this could cause heap pollution. For example:</p> <pre><code>private static &lt;T extends Enum&lt;T&gt; &amp; Marshallable&gt; List&lt;T&gt; unsafeFooHelper(Class&lt;? extends Marshallable&gt; type) { if (type.isEnum()) { //no longer safe! @SuppressWarnings("unchecked") final Class&lt;T&gt; enumType = (Class&lt;T&gt;)type; return Arrays.asList(enumType.getEnumConstants()); } return Collections.emptyList(); } enum Enum1 implements Marshallable { ONE, TWO } enum Enum2 implements Marshallable { A, B } ... //caller lies about what T is: List&lt;Enum2&gt; enumConstants = Main.&lt;Enum2&gt;unsafeFooHelper(Enum1.class); //sometime later... Enum2 enumConstant = enumConstants.get(0); //ClassCastException </code></pre>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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