Sunday, 15 May 2011

Javac type inference bug

Scenario: A generics based configuration reader that worked perfectly fine under Eclipse, suddenly started failing inside a Jenkins build. The cause was a compilation error: "type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object".

According to this bug report, this is an almost 6 years old javac bug. Apprently Java 1.7 fixes it, but I haven't had a chance to verify it. Here's some sample code to reproduce it:


package com.lucidelectricdreams;

public class GenericsTest
{
@SuppressWarnings("unchecked")
public <T> T genericReturnTest(int typeToReturn)
{

switch(typeToReturn)
{
case 1: // integer
return (T)(new Integer(12));

case 2: // double
return (T)(new Double(56.2D));

default: // String
return (T)"test";
}
}


public static void main(String[] args)
{
GenericsTest gt = new GenericsTest();

int intRetVal = gt.genericReturnTest(1);
double doubleRetVal = gt.genericReturnTest(2);
String stringRetVal = gt.genericReturnTest(3);

System.out.println(intRetVal);
System.out.println(doubleRetVal);
System.out.println(stringRetVal);
}
}

 

Changing the main method as follows, gets rid of the compiler error:

public static void main(String[] args)
{
GenericsTest gt = new GenericsTest();

int intRetVal = gt.<Integer>genericReturnTest(1);
double doubleRetVal = gt.<Double>genericReturnTest(2);
String stringRetVal = gt.genericReturnTest(3);

System.out.println(intRetVal);
System.out.println(doubleRetVal);
System.out.println(stringRetVal);
}

No comments: