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

前端 未结 4 1370
无人及你
无人及你 2021-02-20 18:00

I have the following methods:

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

public <         


        
相关标签:
4条回答
  • 2021-02-20 18:21

    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.

    0 讨论(0)
  • 2021-02-20 18:22

    This seems like a failure of inference. The first method clearly intends to call the second method with the type argument being the same type parameter T that it has. But probably the compiler can't figure it out because its inference system is not good enough.

    In any case, you should be able to explicitly specify the type argument and it should get rid of the error:

    public <T> T fromJson( Reader jsonData, Class<T> clazz ) {
        return this.<T>fromJson( jsonData, (Type)clazz );
    }
    
    0 讨论(0)
  • 2021-02-20 18:26

    I too Had a similar issue while compiling in NetBeans. All I had to do was change the JDK version from 16 bit to 32 bit in the Settings > Compile > Java Platform.

    0 讨论(0)
  • 2021-02-20 18:41

    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").

    0 讨论(0)
提交回复
热议问题