Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics: What is the compiler's issue here? ("no unique maximal instance")

I have the following methods:

public <T> T fromJson( Reader jsonData, Class<T> clazz ) {
    return fromJson( jsonData, (Type)clazz );
}

public <T> T fromJson( Reader jsonData, Type clazz ) {
    ...
}

The compiler is saying about the first method:

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

 return fromJson( jsonData, (Type)clazz );
                ^

What is the problem?

like image 906
Epaga Avatar asked Mar 12 '10 08:03

Epaga


2 Answers

The problem is the definition of the second method:

public <T> T fromJson( Reader jsonData, Type clazz ) {

There is no way for the compiler to tell what type T might have. You must return Object here because you can't use Type<T> clazz (Type doesn't support generics).

This leads to a cast (T) in the first method which will cause a warning. To get rid of that warning, you have two options:

  1. Tell the compiler the type. Use this (odd) syntax:

    this.<T>fromJson( jsonData, (Type)clazz );
    

    Note that you need the this here because <T>fromJson() alone is illegal syntax.

  2. Use the annotation @SuppressWarnings("unchecked").

like image 191
Aaron Digulla Avatar answered Nov 15 '22 11:11

Aaron Digulla


I encountered the same problem and found it was a bug (#6302954) in the JDK. It was fixed in jdk 6u25.

I worked around one of the instances of this problem but decided to update the JDK version on the CI box instead.

like image 22
Peter L Avatar answered Nov 15 '22 11:11

Peter L