Note that there are some explanatory texts on larger screens.

plurals
  1. POSun JDK 1.5 cannot dereference error with generics
    primarykey
    data
    text
    <p>We have a class hierarchy similar to this one:</p> <pre><code>public class TestDereference { private static MainInterface mi = new MainInterfaceImpl(); public static void main(String[] args) { System.out.println(mi.getSubInterface().getField()); } } interface MainInterface { &lt;T extends SubInterface&gt; T getSubInterface(); } interface SubInterface { Field getField(); } class Field { @Override public String toString() { return "Hooray!"; } } class SubInterfaceImpl implements SubInterface { Field f = new Field(); public Field getField() { return f; } } class MainInterfaceImpl implements MainInterface { SubInterfaceImpl si = new SubInterfaceImpl(); public &lt;T extends SubInterface&gt; T getSubInterface() { return (T) si; } } </code></pre> <p>The interfaces actually have more than one implementation but that's not the problem. Compiling this with the Eclipse compiler or Java 1.6 works just fine (as seen on <a href="http://www.ideone.com/owQC4" rel="nofollow">ideone</a>). But if I try to compile this with Java 1.5 (which is one of the requirements of our project) gives the following error:</p> <pre><code>TestDereference.java:12: test.SubInterface cannot be dereferenced System.out.println(mi.getSubInterface().getField()); ^ </code></pre> <p>Also note that it doesn't happen with JDK 1.6 using <code>-target 1.5</code> either, only with JDK 1.5</p> <p>The only cases when this error occurs that I found on the web are related to doing things like this:</p> <pre><code>double d = 2.0; d.toString(); </code></pre> <p>where it's obvious what the problem is.</p> <p>But it my case it should work, since it's clear that <code>getSubInterface()</code> returns a <code>SubInterface</code> implementing class that definitely has the <code>getField()</code> method.</p> <p>So is this a compiler bug? And what options do I have besides doing <code>mi.&lt;SubInterface&gt;getSubInterface()</code> every single time (which works, but since Eclipse doesn't mark this as an error, most people on the team forget do it, and most of them use only JDK 1.6 so they don't notice it when compiling with maven/cmd line either)?</p>
    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.
 

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