JDK-6973465 : Type inference fails for primitive types
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 6u21
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2010-07-30
  • Updated: 2012-03-20
  • Resolved: 2010-12-01
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)


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


A DESCRIPTION OF THE PROBLEM :
The Java compiler is able to infer the return value of the getValue() method in the example below when the value is assigned to a reference type, but not when it is assigned to a primitive. Since primitives can't be used as generic type arguments, it seems like the compiler should be able to infer the wrapper type from the primitive and use auto-boxing to perform the assignment.


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Attempt to compile the provided sample code. Compiler errors are generated for lines 6 and 9.


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The program should compile.

ACTUAL -
The program does not compile.


ERROR MESSAGES/STACK TRACES THAT OCCUR :
Line 6 produces: "type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object"

Line 9 produces: "type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds float,java.lang.Object"


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
package com.foo;

public class PrimitiveTypeInferenceTest {
    public static void main(String[] args) {
        Integer i1 = getValue();
        int i2 = getValue();
        
        Float f1 = getValue();
        float f2 = getValue();
    }

    @SuppressWarnings("unchecked")
    public static <T> T getValue() {
        Object o = 0;
        return (T)o;
    }
}

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

CUSTOMER SUBMITTED WORKAROUND :
Workaround is to cast return value to appropriate wrapper type before performing assignment:

int i2 = (Integer)getValue();
float f2 = (Float)getValue();