Question

Let's say I have the following incomplete code:

public class Foo<Type> {
    public Foo() {
        List<Type> list = new ArrayList|
    }
}

where the pipe ("|") after ArrayList indicates the current cursor position.

Now, if I press Ctrl+Space and have Eclipse auto-complete the constructor call on the ArrayList, it generates the following line:

List<Type> list = new ArrayList<Foo.Type>();

and immediately reports an error that "Foo.Type cannot be resolved to a type".

This leaves me with a couple of questions:

Why does Eclipse include Foo. in the auto-completed generic parameter? Is this a bug? Is there a reason why it does this? Can it be turned off? And lastly: Why can Foo.Type not be resolved???

Was it helpful?

Solution

I can at least partially answer your question. First, the easy one. Foo.Type cannot be resolved because that would be an inner class named Type inside the Foo class. In your example, there is no such inner class. Also, in your code, the symbol Type is really a generic type variable, neither the name nor a reference to any specific class. This is easily reproducible, shown here in DrJava, and not specific to your use of Eclipse: Screenshot from DrJava showing compiler error referencing Foo.Type

"Why does Eclipse include Foo." and "Is this a bug?" I think the answer is clearly yes, it is a bug, simply because there's no such thing as Foo.Type in your posted code and as reported by the compiler. But as a bug, it's harder to answer the why part of your question without looking into the Eclipse code, or whatever code Eclipse relies upon for its autocomplete logic. What Eclipse should recommend for you is simply Type. Again, DrJava shows that using <Type> compiles cleanly as expected:

Screenshot from DrJava showing a clean compilation when referencing Type without any qualifier in front of it.

As for turning this behavior off, since I'm not an Eclipse user, the best I can do at the moment is direct you to this related SO question: Disable content assist in Eclipse

While I do not know whether Eclipse is actually relying on compiler type inference to provide the autocomplete suggestion, there have been a number of javac compiler inference bugs over the years, as well as reports of Eclipse behavior not matching javac. Some of these have been javac bugs, others are probably Eclipse issues. A search on the Web for "java type inference bug" yields plenty of hits, but at this point it's just a guess. You didn't specify which version of Java you were using; it might be interesting to try the same code using different versions (JDK 6 vs 7 vs 8).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top