JDK-7043414 : incompatible types error with generic static factory method
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 6u25
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2011-05-10
  • Updated: 2012-09-06
  • Resolved: 2011-05-10
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) Client VM (build 20.0-b11, mixed mode, sharing)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [Version 5.1.2600]

A DESCRIPTION OF THE PROBLEM :
Using a static factory method of a class with a constrained type parameter gives a compiler error: incompatible types.

The class compiles without error when using jdk7 preview or ecj.



STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Compile the class listed under source code:

javac Foo.java


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The class should compile without errors.
ACTUAL -
The compiler reports a type error.

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Foo.java:8: incompatible types; no instance(s) of type variable(s) T exist so that Foo<T> conforms to Foo<java.lang.Integer>
found   : <T>Foo<T>
required: Foo<java.lang.Integer>
        Foo<Integer> obj = emptyFoo();

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public class Foo<T extends Comparable<? super T>> {
    
    public static <T extends Comparable<? super T>> Foo<T> emptyFoo() {
        return new Foo<T>();
    }

    public static void testFact() {
        Foo<Integer> obj = emptyFoo();
    }
    
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Several:

1. The factory method is only used to reduce repetition. Code works just fine if we construct the object directly:

 Foo<Integer> obj = new Foo<Integer>();

2. Use jdk7. Not yet practical for a production release.